CustomListViews in Fragments

Hello, I am a noob developer for android, I am working with Custom List views, adapters,etc on activities and everything has been working good. Recently I am trying to incorporate these custom listviews to Fragments.
This is my code that worked with activitiesÑ
ADAPTER
`class ClientesListViewAdapter : BaseAdapter
{
List items;
Activity context;

    public ClientesListViewAdapter(Activity context, List<Clientes> items)
        : base()
    {
        this.context = context;
        this.items = items;
    }

    #region implemented abstract members of BaseAdapter
    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var item = items[position];
        View view = convertView;
        if (view == null)
        {
            view = context.LayoutInflater.Inflate(Resource.Layout.ClientesCustomView, null);
        }

        view.FindViewById<TextView>(Resource.Id.txtClienteNombre).Text = item.ClienteNombre;
        view.FindViewById<TextView>(Resource.Id.txtClienteCargo).Text = ("Cargo :") + item.ClienteCargo;
        view.FindViewById<TextView> (Resource.Id.txtClienteFaseActual).Text = ("Fase actual: ") + item.ClienteFaseActual;

        return view;
    }

    public override int Count
    {
        get { return items.Count; }
    }

    #endregion
    #region implemented abstract members of BaseAdapter
    public override Clientes this[int position]
    {
        get { return items[position]; }
    }
    #endregion
}

} Activity: public class ClientesActivity : Activity
{
List clientesThisList = new List ();
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.ClientesLayout);
// Create your application here
clientesThisList.Add(new Clientes(1,"Marta Gonzalez", "Presidenta","Supersayayin"));
clientesThisList.Add(new Clientes(2, "Marta ersdfg", "fgfhh", "fdhgj"));

        ListView clientesListView = FindViewById<ListView>(Resource.Id.clientesListView);
        clientesListView.Adapter = new ClientesListViewAdapter(this, clientesThisList);
        // Create your application here
    }
}`

And with the fragment I use the same adapter but in the fragment when i attempt to use this line it throws me a 4 errors:
clientesListView.Adapter = new ClientesListViewAdapter(this, clientesThisList);

Can anyone please help me to adapt my activity code into a Fragment or ListFragment functional code? I have spent 3 days without any luck.
Your help will be appreciate.

This is my "ListFragment" code so far:

`public class ClientesFragment : ListFragment
{
List clientesThisList = new List ();
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{

        // A large amount of text to display.
        //var view = inflater.Inflate(Resource.Layout.ClientesLayout, container, null);
        var view = inflater.Inflate(Resource.Layout.ClientesLayout, null);

// clientesThisList.Add(new Clientes(1,"Marta Gonzalez", "Presidenta","Supersayayin"));
// clientesThisList.Add(new Clientes(2, "Marta ersdfg", "fgfhh", "fdhgj"));
ListView listview;
listview = view.FindViewById (Resource.Id.clientesListView);
ListView.Adapter = new ClientesListViewAdapter (this, ClientesListViewAdapter);
//listview.Adapter = new ClientesListViewAdapter (this, clientesThisList);
return view;
}
}`

Posts

  • CheesebaronCheesebaron DKInsider, University mod

    If you are implementing a custom ListView in a Fragment do not use ListAdapter.

  • ActivamosDevActivamosDev MXMember

    Thanks for your reply Cheesebaron, can you elaborate a little more?
    I´m little lost here, what should I use instead of ListAdapter?
    Thanks in advanced!

  • CheesebaronCheesebaron DKInsider, University mod

    Sorry I meant to write ListFragment. Don't use a ListFragment when using a custom ListView, use a normal Fragment.

  • ActivamosDevActivamosDev MXMember
    edited May 2014

    Thank you but I can't make it work, this is my fragment code to call the activity that holds the custom view:
    `
    public class ClientesFragment : Fragment
    {
    List clientesThisList = new List ();
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {

            View view = inflater.Inflate(Resource.Layout.ClientesLayout, null);
            return view;
        }
    }
    

    `
    In this case it shows an empty screen, but if i change the layout resource in the inflater to my raw custom view:

    View view = inflater.Inflate(Resource.Layout.ClientesCustomView, null);
    I get only the first element of my list.
    How can I show the whole list view?
    I really appreciate your help!

  • CheesebaronCheesebaron DKInsider, University mod

    Please format your code or make a reproducible sample on GitHub or similar.

    If you paste the code here, mark it and press the C button in the toolbar it will be a lot easier to read it.

  • ActivamosDevActivamosDev MXMember

    ADAPTER:

    class ClientesListViewAdapter : BaseAdapter { List items; Activity context;
    
        public ClientesListViewAdapter(Activity context, List<Clientes> items)
            : base()
        {
            this.context = context;
            this.items = items;
        }
    
        #region implemented abstract members of BaseAdapter
        public override long GetItemId(int position)
        {
            return position;
        }
    
        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            var item = items[position];
            View view = convertView;
            if (view == null)
            {
                view = context.LayoutInflater.Inflate(Resource.Layout.ClientesCustomView, null);
            }
    
            view.FindViewById<TextView>(Resource.Id.txtClienteNombre).Text = item.ClienteNombre;
            view.FindViewById<TextView>(Resource.Id.txtClienteCargo).Text = ("Cargo :") + item.ClienteCargo;
            view.FindViewById<TextView> (Resource.Id.txtClienteFaseActual).Text = ("Fase actual: ") + item.ClienteFaseActual;
    
            return view;
        }
    
        public override int Count
        {
            get { return items.Count; }
        }
    
        #endregion
        #region implemented abstract members of BaseAdapter
        public override Clientes this[int position]
        {
            get { return items[position]; }
        }
        #endregion
    }
    }
    

    ACTIVITY

     public class ClientesActivity : Activity { 
     List clientesThisList = new List (); 
     protected override void OnCreate(Bundle bundle) { 
     base.OnCreate(bundle); 
     SetContentView(Resource.Layout.ClientesLayout); 
    
     clientesThisList.Add(new Clientes(1,"Marta Gonzalez", "Presidenta","Supersayayin")); 
     clientesThisList.Add(new Clientes(2, "Marta ersdfg", "fgfhh", "fdhgj"));
    
            ListView clientesListView = FindViewById<ListView>(Resource.Id.clientesListView);
            clientesListView.Adapter = new ClientesListViewAdapter(this, clientesThisList);
            // Create your application here
        }
    }
    

    FRAGMENT:

     public class ClientesFragment : Fragment { 
     List clientesThisList = new List (); 
     public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            View view = inflater.Inflate(Resource.Layout.ClientesLayout, null);
            return view;
        }
    }
    

    With this line changed it shows only the first item of the list:

    View view = inflater.Inflate(Resource.Layout.ClientesCustomView, null);

  • CheesebaronCheesebaron DKInsider, University mod

    I don't see anywhere where you are actually using your Fragment.

  • ActivamosDevActivamosDev MXMember

    I forgot this: I used a tabbed layout using action bar

    [Activity(Theme = "@style/Theme.White", Label = "SolicitudDetallesTabActivity")]            
        public class SolicitudDetallesTabActivity : Activity
        {
            //static readonly string Tag = "DetallesSolicitud";
            Fragment[] _fragments;
    
            protected override void OnCreate (Bundle bundle)
            {
                base.OnCreate (bundle);
                SetContentView (Resource.Layout.SolicitudDetallesTabsLayout);
                ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
                // Recibimos el valor de FasesActivity
                String grupoSeleccionado = Intent.GetStringExtra ("grupoSeleccionado") ?? "No has seleccionado fase";
    
                AddTabToActionBar(Resource.String.solicitud_tab_label);
                AddTabToActionBar(Resource.String.clientes_tab_label);
                AddTabToActionBar(Resource.String.referencias_tab_label);
    
                _fragments = new Fragment[]
                {
                    new SolicitudDetallesFolder.SolicitudFragment(),
                    new SolicitudDetallesFolder.ClientesFragment(),
                    new SolicitudDetallesFolder.ReferenciasBancariasFragment()             
                };
    
                // ---------------------------------------------------------
                ActionBar.SetHomeButtonEnabled (true);
                ActionBar.SetDisplayHomeAsUpEnabled (true);
                ActionBar.Title = grupoSeleccionado;
            }
            void AddTabToActionBar(int labelResourceId)
            {
                ActionBar.Tab tab = ActionBar.NewTab ()
                    .SetText (labelResourceId);
                tab.TabSelected += TabOnTabSelected;
                ActionBar.AddTab(tab);
            }
    
            void TabOnTabSelected(object sender, ActionBar.TabEventArgs tabEventArgs)
            {
                ActionBar.Tab tab = (ActionBar.Tab)sender;
    
                Fragment frag = _fragments[tab.Position];
                tabEventArgs.FragmentTransaction.Replace(Resource.Id.frameSolicitudDetalles, frag);
                Android.Widget.Toast.MakeText (this, frag.ToString (), Android.Widget.ToastLength.Short).Show ();
    
            }
            public override bool OnOptionsItemSelected (IMenuItem item)
            {
                switch (item.ItemId) {
                case Android.Resource.Id.Home:
                    Finish ();
                    return true;
                default:
                    return base.OnOptionsItemSelected (item);
                }
            }
            public override bool OnCreateOptionsMenu (IMenu menu)
            {
                base.OnCreateOptionsMenu (menu);
                MenuInflater inflater = this.MenuInflater;
                inflater.Inflate (Resource.Menu.subFases_menu, menu);
    
                return true;
            }
        }
    }
    
  • CheesebaronCheesebaron DKInsider, University mod

    Can you show how you define clientesListView?

  • ActivamosDevActivamosDev MXMember
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:minWidth="25px"
        android:minHeight="25px"
        android:divider="#DDDDDD"
        android:dividerHeight="5px">
        <ListView
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/clientesListView" />
    </LinearLayout>
    
  • CheesebaronCheesebaron DKInsider, University mod

    Are you sure you want the height of the ListView to be wrap_content?

  • ActivamosDevActivamosDev MXMember

    Well I have changed ti so many times, I don´t think that it´s the problem, right now I'm testing with fill_parent and it doesn't show anything....

  • CheesebaronCheesebaron DKInsider, University mod

    Not really sure what you are doing, but it kind of seems strange to that you both have an Activity and a Fragment using the clientesListView. Where are you changing to the ClientesActivity? Where are you populating the ClientesFragment with an Adapter?

  • wonderWomanwonderWoman USMember

    if i understand true you can use adapters in fragments like that..

    public ClientesListViewAdapter(Activity context, List<Clientes> items) : base() 
              {
                    this.context = context;
                    this.items = items;
                }
    

    // replace this

    public ClientesListViewAdapter(Fragment context, List<Clientes> items) :  base()
             {
                    this.context = context.Activity;
                    this.items = items;
                }
    
  • ActivamosDevActivamosDev MXMember

    I wanted to use the Action Bar tab layout and what I read is that it works with fragments, so I inflate my already made layout from a fragment and I populate the list views from the activity:

    public class ClientesActivity : Activity
        {
            List<Clientes> clientesThisList = new List<Clientes> ();
            protected override void OnCreate(Bundle savedInstanceState)
            {
                base.OnCreate(savedInstanceState);
                SetContentView(Resource.Layout.ClientesLayout);
                clientesThisList.Add(new Clientes(1,"Marta Gonzalez", "Presidenta","Supersayayin"));
                clientesThisList.Add(new Clientes(2, "Marta ersdfg", "fgfhh", "fdhgj"));
    
                ListView clientesListView = FindViewById<ListView>(Resource.Id.clientesListView);
                clientesListView.Adapter = new ClientesListViewAdapter(this, clientesThisList);
            }
        }
    

    So basically I only use the fragment as a medium to use the activity with action bar tabs

  • CheesebaronCheesebaron DKInsider, University mod

    That won't work. You have to populate the list inside the Fragment if that is what you are showing. You can't just randomly make an Activity, not use it and expect that the ListView inside the Fragment gets populated...

  • ActivamosDevActivamosDev MXMember

    But when I try to populate it directly in the Fragment, my code doesn't work, do you have a guide on How to populate a Fragment using a custom list view? I'm trying to populate my fragment with this code:

    public class ClientesFragment : Fragment
            {
                List<Clientes> clientesThisList = new List<Clientes> ();
                public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
                {
    
                    View view = inflater.Inflate(Resource.Layout.ClientesCustomView, null);
                    clientesThisList.Add(new Clientes(1,"Marta Gonzalez", "Presidenta","Supersayayin"));
                    clientesThisList.Add(new Clientes(2, "Marta ersdfg", "fgfhh", "fdhgj"));
                    ListView client = view.FindViewById<ListView> (Resource.Id.clientesListView);
                    client.Adapter = new ClientesListViewAdapter(this, clientesThisList);
                    return view;
                }
            }
    

    but it says that it can't convert a Fragment to Activity, so how can I make this work??

  • CheesebaronCheesebaron DKInsider, University mod

    Instead of this use this.Activity because you are in a Fragment.

  • KeyzerSKeyzerS NOMember ✭✭

    Seems like the question-maker here never came back. I just want to say thanks a lot for the answers here. They saved me when i got stuck. Havent worked with fragments before, and it confuses me.

  • ActivamosDevActivamosDev MXMember

    sorry,
    the this.Activity worked for me. I don't know how to mark this question as answered.
    Thanks for the help, everyone!!!

  • JhonSahaJhonSaha USMember

    @wonderWoman greatttttt ... it's work for me , thanks

  • SumitmPathakSumitmPathak USMember ✭✭

    Awesome... This works for me... Thanks @Cheesebaron and @wondorWom

  • VaibhavPatilVaibhavPatil USMember ✭✭

    Hey guys,

    I have generated code from above code samples But i still getting error as unhandled exception

    Following is my code

    ClientesFragment :

    `public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

            View view = inflater.Inflate(Resource.Layout.ClientesCustomView, null);
            //clientesThisList.Add(new Clientes("Marta Gonzalez", "Presidenta", "Supersayayin"));
            //clientesThisList.Add(new Clientes("Marta ersdfg", "fgfhh", "fdhgj"));
    
            string results = "";
            using (WebClient wc = new WebClient())
            {
                results = wc.DownloadString("my_api_url");
            }
    
            clients = JsonConvert.DeserializeObject<RootObject>(results);
    
            ListView client = view.FindViewById<ListView>(Resource.Id.clientesListView);
            client.Adapter = new ClientesListViewAdapter(this.Activity, clients.clientes);
            return view;
        }`
    

    If i set view layout as ClientesLayout getting unhandled exception while returning view.
    If i set view layout as ClientesCustomView getting null listview; (I know ClientesCustomView doesn't contain any listview ).

    I don't know how it's worked for @ActivamosDev

Sign In or Register to comment.