Why do ListView items not grow to wrap their content?

前端 未结 9 645
猫巷女王i
猫巷女王i 2020-11-30 20:26

I have a rather complex ListView, with variable list item heights. Under certain conditions, I need to display an additional view in a list item, which is hidden by default

相关标签:
9条回答
  • 2020-11-30 21:00

    How are you inflating your rows?

    If you are not using it right now, try using LayoutInflater#inflate(layoutId, parent, false) (where parent is the AdapterView supplied to getView() or newView()):

    v = getLayoutInflater().inflate(R.layout.list_item, parent, false);
    
    0 讨论(0)
  • 2020-11-30 21:03

    Try this: http://www.java2s.com/Code/Android/UI/setListViewHeightBasedOnChildren.htm

    public class Utils {
    
        public static void setListViewHeightBasedOnChildren(ListView listView) {
            ListAdapter listAdapter = listView.getAdapter(); 
            if (listAdapter == null) {
                // pre-condition
                return;
            }
    
            int totalHeight = 0;
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }
    
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
            listView.setLayoutParams(params);
            listView.requestLayout();
        }     
    }
    
    0 讨论(0)
  • 2020-11-30 21:07

    If you're using a custom View in as the list item that is resizing, then you can take from PeBek's answer and do this when you construct the View

    addOnLayoutChangeListener(
                new OnLayoutChangeListener() {
                    @Override
                    public void onLayoutChange(View _, int __, int ___, int ____, int bottom, int _____, int ______,
                                               int _______, int old_bottom) {
                        final ListView list_view = (ListView) getParent();
                        final ViewGroup.LayoutParams params = list_view.getLayoutParams();
                        params.height += bottom - old_bottom;
                        list_view.setLayoutParams(params);
                        list_view.requestLayout();
                    }
                });
    

    When the View gets resized this callback method will me run and it updates the ListView height to include the change in height (delta bottom). The other values, if they prove useful for you are view (reference to the view), left, top, right, bottom, old_left, old_top, old_right, old_bottom. It works for expanding and collapsing the view.

    API 11 is required for OnLayoutChangeListener, don't know if there's a backward compatible way to do so.

    0 讨论(0)
提交回复
热议问题