Vickyexpert
Vickyexpert

Reputation: 3167

Set dynamic height for list view which is added programatically in android

Please don't mark as duplicate this question without understanding.

I have gone through all answers which are available but none is able to resolve my issue.

Scenario: I have to add Sections with feature of expand and collapse on click, these sections are dynamic as per API response. So I have taken On xml file with below tree structure.

main.xml

LinearLayout->ScrollView->LinearLayout

Now I am adding custom xml design file in this linear layout as per response, also this response contains number of questions in each section. So for managing questions, I have taken listview in custom xml file. Now I have to show each listview in full height so only top scroll should work no any kind of scroll inside section.

I have checked some answers with common method name setListViewHeightBasedOnChildren but it is not working as listview is added run time dynamically.

So please help me for this.

Upvotes: 4

Views: 529

Answers (2)

Sagar
Sagar

Reputation: 554

I have done this, try this:

  public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        // pre-condition
        return;
    }

    int totalHeight = 0;
    int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
    listView.requestLayout();
}

Upvotes: 1

Uma Achanta
Uma Achanta

Reputation: 3729

As the number of sub lists are dynamic, you better go through the library

You just need to add one more adapter to maintain sublists. its pretty easy to customize as well.

https://github.com/luizgrp/SectionedRecyclerViewAdapter

Upvotes: 1

Related Questions