Listview with dynamic height(without scroll)

Asked

Viewed 542 times

0

Considering the following structure:

Listview (1) > Adapter (1) > Listview (2) > Adapter (2)

I need to place a listview inside an Adapter, and in that list view there may be several other Adapters.

Adapter(1) inside Listview(1) needs to contain a Listview(2) and within that precise list of Adapters(2) with heights according to its contents.

I’ve tried everything I’ve seen in tutorials and nothing helped, always the same thing happens. Adapter(1) is fixed in size, and Listview(2) creates scrolling, it is not full in height to readjust the Adapter(1).

I leave below an image with example and caption, and thank you if someone can tell me how I can be making this list. Thank you.

Mockup de como ficaria a listagem

1 answer

0

You need to calculate the height of your listview according to the number of items, that’s it?

I use this code:

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

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

        if(listItem != null){
            // This next line is needed before you call measure or else you won't get measured height at all. The listitem needs to be drawn first to know the height.
            listItem.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
            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();
}

Then you just call him, so:

setListViewHeightBasedOnChildren(instancia_da_sua_list_view);
  • Hello Leandro, perfect understood the logic but my Adapter(1) is picking 100% of the screen, it is not getting proportional to listview

  • You leave content with wrapcontent?

  • This, you can leave the height in wrap_content, this method will set the height for you, just remember to call it after the listview is populated.

  • call him after lstView.setAdapter(Adapter);

  • lstView is my listview 2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.