android动态设置listview高度

ala*_*731 5 height android listview params

我有ExpandableListview内部ScrollView,我知道这不好,但我也有,显示整个列表的唯一解决方案是通过使用代码设置其高度layoutParams

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,ListViewData.length());

这个解决方案很好但我无法确定我应该给出的正确高度,Params所以有没有办法从阵列的大小知道实际大小

编辑: 我提出了一个解决方案,每当我扩展一组列表时我会改变高度以适应新的geight

Mur*_*san 14

试试这个,基于listview使用Child.setListViewHeightBasedOnChildren()这将根据listview设置基于身高的高度

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



}
Run Code Online (Sandbox Code Playgroud)

  • 不工作,高度应该比它应该大 (4认同)

She*_*tib 10

在这种情况下,您的ListView实际上是不必要的.您也可以遍历适配器的项目,只需将它们添加到ScrollView中的垂直LinearLayout即可.

如果您不想更改大量代码:

替换ListView.setAdapter

LinearLayout ll; //this should be the vertical LinearLayout that you substituted the listview with
for(int i=0;i<adapter.getCount();i++) {
    View v = adapter.getView(position, null, null);
    ll.addView(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
Run Code Online (Sandbox Code Playgroud)

如果您已View v = adapter.getView(position, null, null);在以下后面使用OnItemClickListener添加

final int position = i;
v.setOnClickListener(new OnClickListener() {
    public onClick(View v) {
        yourOnItemClickListener.onItemClick(null, v, position, 0);
    }
});
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您不必担心高度上的任何误算.


Pal*_*avi 0

您可以在尺寸文件中为不同的屏幕尺寸设置一个变量,然后将其乘以要显示的列表项目数。