2013-02-14 79 views
0

如何以编程方式设置ListItems的高度和/或如何以编程方式创建ListItems?我目前使用自定义ListItem.xml与自定义适配器,但ListItems只有一个固定的高度。这会创建大量未使用的空间,因为ListItems的内容不相同。 有没有解决这个问题的方法?Dynamic ListItem高度

+0

请张贴一些代码... – Anukool 2013-02-14 12:19:33

回答

0

您应该使用自定义数组适配器,并且取决于您的物品的内容,您可以更改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。

我编辑更explicative版本:

在适配器的时候有:getView(int position, View convertView, ViewGroup parent)

,你可以为你的愿望的convertView分配或多或少的高度修改。如果你不发布一些代码,我不能帮助更多的抱歉。

+0

你的样品还使用了ListItem.xml,但不帮我。就像我说的,我的ListItems的内容是不同的,所以我需要一个解决方案来以编程方式设置高度。 – 2013-02-14 12:28:08

0

试试这个:

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