Reference dynamically created ImageView

PrescottChartierPrescottChartier ✭✭USMember ✭✭
edited September 2015 in Xamarin.Android

I'm trying to reference an ImageView added to the layout dynamically.

I've created a ImageView as such:

        var layout = new LinearLayout(this);
        layout.Orientation = Orientation.Vertical;
        layout.AddView(image,0);
        SetContentView(layout);

Now I'd like to be able to reference the ImageView later in a function later in my code like this:

    protected  override void OnActivityResult(int requestCode, Result resultCode, Intent data)
    {
        base.OnActivityResult(requestCode, resultCode, data);
        if (requestCode == TakePictureRequestCode)            {
            // var picture = FindViewById<ImageView>(Resource.Id.image);
            try
            {
                var bitmap = (Bitmap)data.Extras.Get("data");
                ImageView MyImage = FindViewById<ImageView>(0);
                MyImage.SetImageBitmap(bitmap);
            }
            catch (Exception e)
            {
                var error = e.Message;
            };
        }
    }

when trying to execute MyImage.SetImageBitmap(bitmap); I get "Object reference not set to an instance of an object". Obviously this doesn't work. Anyone know how this can be accomplished?

Scott ....

Answers

  • PrescottChartierPrescottChartier ✭✭ USMember ✭✭

    Ok, solved it:

    At the top of the calling activity, before the protected override void OnCreate(Bundle bundle) statement I added the following:

    public ImageView MyImageView;

    below the protected override void OnCreate(Bundle bundle) statement I added:

    MyImageView = new ImageView(this);

    Then I added it to the layout
    var layout = new LinearLayout(this);
    layout.Orientation = Orientation.Vertical;
    layout.AddView(MyImageView);
    SetContentView(layout);

    The result is that I have a globally accessible variable that can be set from within OnActivityResult,(or anywhere else) like so:

        protected  override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
    
            if (requestCode == TakePictureRequestCode)
            {
                try
                {
                    var bitmap = (Bitmap)data.Extras.Get("data");
                    MyImageView.SetImageBitmap(bitmap); // Now globally accessible
                }
                catch (Exception e)
                {
                    var error = e.Message;
                };
            }
        }
    
Sign In or Register to comment.