Skip to content
Advertisement

Adding a ListView in a Fragment

I want to add a ListView to a Fragment. I created a FrameLayout in my activity_main.xml and then created 3 fragments (Home, Tags, Settings). What I did was create a bottom navigation view and created 3 frame layouts for the mentioned fragments.

I searched the whole web on how to add a ListView to a Fragment, but whatever code they say is deprecated. I just want to add a ListView to the settings fragment. The code is below:

JavaScript

This is my XML code:

JavaScript

Can anyone please help me with the updated code for doing this? Thanks in Advance!

Advertisement

Answer

I’m going to assume you got the fragment to show on screen successfully and you just want to add a simple ListView. Here’s how you do it:

1- Add the ListView to your fragmnet xml with an id:

JavaScript

2- Get a reference to it in onCreateView of your fragment:

JavaScript

3- Create a Custom Adapter for your ListView that extends BaseAdapter:

JavaScript

I created a simple one here that only makes hosts a list of strings and displays each with a TextView, but you can replace it with whatever you want.

4- Set the adapter of the ListView to your custom adapter:

JavaScript

Done. You get a ListView in the fragment with all the items. As others have pointed out, ListView is not preferred when you have a large list of items, it’s bettter to use RecyclerView in that case.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement