ROn ROn - 2 months ago 36
C# Question

How to create a ListView In Fragment for Xamarin Android

I want to create a ListView in Fragment using Xamarin Android.

Code as follows
1. Framgent2.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Support.V4.App;
namespace NavigationDrawerTest
{
public class Fragment2 : Android.Support.V4.App.Fragment
{
private List<string> mItems;
private ListView mListView;

public override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
//SetContentView (Resource.Layout.Fragment2_Layout);
mListView = FindViewById<ListView>(Resource.Id.myListView);

mItems = new List<string> ();
mItems.Add ("One");
mItems.Add ("Two");
mItems.Add ("Three");
mItems.Add ("Four");
mItems.Add ("Five");

ArrayAdapter <string> adapter = new ArrayAdapter<string> (this, Android.Resource.Layout.SimpleListItem1, mItems);
mListView.Adapter = adapter;
}

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


return view;
}


}
}


error in this code as follows

Fragment2.cs error image


  1. Code as follow Fragment2_layout.axml



Fragment2_layout.axml code as image

Answer
   public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.Inflate(Resource.Layout.Fragment2_Layout, container, false);
        mListView = view.FindViewById<ListView>(Resource.Id.myListView);

        mItems = new List<string> ();
        mItems.Add ("One");
        mItems.Add ("Two");
        mItems.Add ("Three");
        mItems.Add ("Four");
        mItems.Add ("Five");

        ArrayAdapter<string> adapter = new ArrayAdapter<string>(Context, Android.Resource.Layout.SimpleListItem1, objects: mItems.ToArray());

        mListView.Adapter = adapter;

        return view;
    }

if your only purpose is to manage a ListView then checkout ListFragment

Comments