ListView with dynamic height (without scroll)

0

Considering the following structure:

  

ListView (1) > Adapter (1) > ListView (2) > Adapter (2)

I need to put a listview inside an adapter, and in that list view there may be several other adapters.

The Adapter (1) inside the ListView (1) must contain a ListView (2) and within that precise list of Adapters (2) with heights according to their content.

I've tried everything I've seen in tutorials and nothing has worked, it's always the same. The Adapter (1) is fixed in size, and ListView (2) creates the scroll, it is not full in height to readjust the Adapter (1).

I leave below an example image and caption, and thank you if anyone can let me know how I can be making this list. Thank you.

    
asked by anonymous 26.08.2016 / 14:43

1 answer

0

You need to calculate the height of your listView according to the number of items, is that?

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

Just call it, like this:

setListViewHeightBasedOnChildren(instancia_da_sua_list_view);
    
26.08.2016 / 15:00