如何以编程方式调整ListView的大小

时间:2019-04-17 17:56:45

标签: android

我正在开发一个新的应用程序,我想以编程方式调整ListView的大小,例如,从参数为200x100的ListView调整为100x100。

如何调整ListView的尺寸?

1 个答案:

答案 0 :(得分:1)

public void setListViewHeightBasedOnChildren(ListView listView) {
         ArrayAdapter listAdapter = (ArrayAdapter) 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();
        }