Grid view worked in activity, not working in fragment. How do I fix this?

I have a grid view that's working perfectly when I use it in an activity, but when I try to use it in a fragment I get a System.NullReferenceException at the row where I call the adapter. I've tried adapting the code for use in a fragment, but I guess I'm doing something wrong. What am I doing wrong and what can I do about it?

Here's the code for the fragment:

public class SituationFragment : Fragment
{
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        var view = inflater.Inflate(Resource.Layout.situationButtonGrid, container, false);

        List<string> situationTitles = new List<string> {"Name 1","Name 2","Name 3"};
        var gridViewSituation = Activity.FindViewById<GridView> (Resource.Id.situationButtonGridView);
        gridViewSituation.Adapter = new SituationButtonAdapter (this.Activity, situationTitles);
        return view;
    }
}

Posts

  • EvilGeniusJamieEvilGeniusJamie GBMember
    edited September 2013
    var gridViewSituation = view.FindViewById<GridView> (Resource.Id.situationButtonGridView);
    

    The activity does not contain this view until the last line:

    return view;
    

    So you will not be able to find the GridView on the activity. Targeting the view instead of Activity solves this.

  • KurodaniKurodani SEMember

    Thanks for the help EGJ, that was the problem ^^

Sign In or Register to comment.