如何以编程方式设置ListItems的高度和/或如何以编程方式创建ListItems?我目前使用的是带自定义适配器的自定义ListItem.xml,但ListItems只有固定的高度。这会产生大量未使用的空间,因为ListItems没有相同的内容。这个问题有什么解决方案吗?
发布于 2013-02-14 20:20:06
您应该使用自定义数组适配器,并且可以根据项目的内容更改itemView的高度。你可以在谷歌上找到一些例子。
http://sogacity.com/how-to-make-a-custom-arrayadapter-for-listview/
http://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/
在arrayAdapter中,您可以检查是否有字段,并设置此“字段视图”高度=0,例如,或View.INVISIBLE。
我为更明确的版本编辑的:
在您的适配器中有:getView(int position, View convertView, ViewGroup parent)
您可以根据自己的意愿修改convertView以分配或多或少的高度。如果你不张贴一些代码,我无法帮助更多的抱歉。
发布于 2013-02-14 20:40:04
试试这个:
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();查看此链接将对您有所帮助,http://kk-brothers.blogspot.in/2011/09/dynamically-change-listview-height.html
https://stackoverflow.com/questions/14874658
复制相似问题