Search code examples
androidlistlistviewrowandroid-listfragment

How to create my own ListFragment in Android?


In a normal ListView, I can usually create my own style for a single row.

How can I do it when I have a ListFragment?

I know that I have to change the second parameter in this line:

setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list_items));

But, what if the single row has more than three values?


Solution

  • By calling getListView() inside a ListFragment you'll get the corresponding ListView returned and can do whatever you want with it.

    Regarding your second question: If you want to control the behaviour of the adapter just build your own custom adapter. It requires a little work the first time but you'll need and use it a lot, once you learned how to do it.

    There are a lot of tutorials out there about this, e.g. this one. Be sure to also use the holder pattern for optimized performance.

    The result could look like this

    MyCustomAdapter adapter = new MyCustomAdapter(itemList, context);
    ...
    getListView().setListAdapter(adapter);