Laser42
Laser42

Reputation: 744

Xamarin, assign image to ImageView in Fragment

How can I assign a drawable png to ImageView in Fragment? I declare an ImageView in tab's layout:

ImageView

      android:layout_width="fill_parent"
      android:layout_height="wrap_content "
      android:layout_rowSpan="2"
      android:id ="@+id/iv_icon"

The tab class is here:

class tabFragment1 : V4Fragment

{

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle saved)
    {
        var v = inflater.Inflate(Resource.Layout.tabLayout1, container, false);
        return v;
    }

}

I want to assign an .png from drawable folder , something like this:

ImageView iv_icon = FindViewById(Resource.Id.iv_icon); iv_icon.SetImageResource(Resource.Drawable.ic_weather_cloudy_white_48dp);

If I put it in the MainActivity OnCreate() method (below the ViewPager initialisation, of course), I get NullRefenceException Error (on the second row). The question is: in which class should I put these statements?

Thanks!

Upvotes: 0

Views: 408

Answers (2)

pinedax
pinedax

Reputation: 9346

In your Fragment OnCreateView once you had inflated the view/layout you can access its ui elements, in your case your ImageView.

Modify this method:

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle saved)
{
    var v = inflater.Inflate(Resource.Layout.tabLayout1, container, false);

    ImageView iv_icon = v.FindViewById(Resource.Id.iv_icon); 

    iv_icon.SetImageResource(Resource.Drawable.ic_weather_cloudy_white_48dp);

    return v;
}

Hope this helps.-

Upvotes: 1

Shane Sepac
Shane Sepac

Reputation: 826

The problem lies in the instantiation of your ImageView. You can't just call FindViewById, you have to call FindViewById from your fragment reference. Such as:

ImageView iv_icon = fragmentName.FindViewById(Resource.Id.iv_icon); 
//fragmentName is the reference to your fragment *after its been inflated*

The exception is being thrown because your trying to call SetImageResource from an ImageView that was instantiated improperly. The ImageView is null and hence a NullReferenceException is being thrown.

On a side note, inflation of a view from an Activity will work as follows:

View v = FindViewById(Resource.Id.X);

FindViewById is a convenience method so that you don't have to keep calling activityName.FindViewById(). This convenience does not exist for fragments.

In summary, inflating a view from an Activity:

View v = FindViewById(Resource.Id.X);

Inflating a view from a fragment:

View v = fragmentName.FindViewById(Resource.Id.X);

Upvotes: 1

Related Questions