Set dynamic height to view a list that is added programmatically in android

Please do not mark how to duplicate this question without understanding.

I went through all the available answers, but no one can solve my problem.

Scenario: . I need to add sections with the expand and collapse function by clicking, these sections are dynamic in accordance with the API response. Therefore, I took an xml file with a lower tree structure.

main.xml

LinearLayout-> ScrollView-> LinearLayout

Now I am adding a custom xml design file to this line layout according to the answer, also this answer contains the number of questions in each section. Therefore, to manage questions, I took a listview in a custom XML file. Now I need to show each list at full height, so only the top scroll will not work in any scroll inside the section.

I checked several answers with the common name of the setListViewHeightBasedOnChildren method , but it does not work as listview adds runtime dynamically.

So please help me with this.

+4
source share
2 answers

Since the number of subscriptions is dynamic, you better go through the library

. , .

https://github.com/luizgrp/SectionedRecyclerViewAdapter

+2

, :

  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();
}
+1

Source: https://habr.com/ru/post/1692305/


All Articles