Android ListView中根据内容(ListView的Item的数量)动态设定ListView的高度
listView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 400*listView.getCount()));
但是上面的代码是有问题的,当在不同像素的手机上使用上面代码时设定高度是不一样的,如何解决这一问题:
可以将设定的高度转化为像素:
public int DpToPx(Context context, float number) {
float scale = context.getResources().getDisplayMetrics().density;
return Math.round(scale);
}
因此,在给ListView设定高度时,可采用:
listView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DpToPx(content, 400) * listView.getCount()));
常量400根据ListView的单个Item的高度决定,上面的代码可以对应不同像素的手机,给ListView动态设定高度。