Saim Mahmood
Saim Mahmood

Reputation: 446

Custom list view with custom adapter in a fragment

I am making an app in which I have an activity that has bottom navigation bar and navigation bar implemented. When I load another activity through intent, it loads the page but both the navigation bar vanish. But, when I load a fragment class both the navigation bar are shown which work too and the page also loads.

I have implemented listview with custom adapter in an avtivity extended class but I am not able to do this for a fragment class. I have seen many tutorials but all of them use a predefined Array adapter. I want each row of my list to contain a relative layout.

Any help would be appreciated. Thanks.

Upvotes: 0

Views: 324

Answers (1)

Ali Nasir
Ali Nasir

Reputation: 217

Yes. There are many ways, but the way I did it was very different (thats what I think). All you need to do are follow the steps I have listed down.

Step # 1: paste your list view code (and remove the table layouts if you were using them before, otherwise no worries) into your xml file. Also, delete scrollviews from your xml since they cause a problem with your listview.

Step # 2: initialize the listview by making the object into java and giving it its correct id through findViewById

Step # 3: Make the custom layout you want for each for row of your listview. For example, a relative layout with 2 textviews and a picture etc etc. Use your imagination here :p

Step # 4: Since in fragments you have to use context or a view variable to give ID's of variables from xml. For that, we get three objects from the onCreateView method and they are:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)

Make a global variable for LayoutInflater and set it equal to this inflater and use the global inflater to initialize views and etc. Like this:

LayoutInflater global;
global = inflater;
view = global.inflate(R.layout.your_frag_id, container, false);

Step # 5: For custom adapters, you have to give them a different view from where they get ID's for their row items. In Activity extended classes its easy but its not the case in Fragments. Its done like this.

public View getView(int i, View view, ViewGroup viewGroup) {
  view = global.inflate(R.layout.your_seperate_xml_id_for_each_row_of_the_list_view, null);}

Step # 6: Now, you can just simply add the values using the listView.setAdapter function.

Upvotes: 1

Related Questions