pigninja
pigninja

Reputation: 57

Not sure where to place fragment activity code

I'm new to Xamarin and new to Android development (this is my first week coming from a windows background). I have an adapter that I'm attempting to add to a listview but I'm not sure where to place my code. I have multiple fragments being inflated from a flyout menu. I attempted placing the code in the fragment itself but this caused compilation errors, I also attempted placing the code in the main activity. Neither seemed to work correctly.

This is the code segment

var items = new String[] { "test", "test2" };
        ArrayAdapter<string> adapter = new ArrayAdapter<string> (this, Android.Resource.Layout.SimpleListItem1, items);
        var listViewMeds = FindViewById<ListView> (Resource.Id.medicationListView);
        listViewMeds.Adapter = adapter;

Upvotes: 0

Views: 128

Answers (1)

Johan
Johan

Reputation: 8276

You will do this in the OnCreateView inside the fragment.

eg

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
            var view = inflater.Inflate(Resource.Layout.MyLayoutId, container, false);

            ListAdapter = new MyAdapter(Activity, Items);
            return view;
}

Note that your fragment will need to be a ListFragment to be able to access the ListAdapter property.

Alternatively, if you don't have a ListFragment you can find your list view in the OnCreateView, eg.

 public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        var view = inflater.Inflate(Resource.Layout.MyLayoutId, container, false);

        var myListView = view.FindViewById<ListView>(Resource.Id.MyListViewId);
        myListView.ListAdapter = new MyAdapter(Activity, Items);
    }

Upvotes: 1

Related Questions