如何设置ListView的高度。
XML代码(此代码工作正常,固定高度为200 d)
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dip"
android:orientation="vertical" >
<ListView
android:id="@+id/dialog_ListView"
android:layout_width="wrap_content"
android:layout_height="200dip"
android:padding="5dip"
android:layout_weight="1"
android:dividerHeight="5dip"
android:divider="@android:color/transparent" />
</LinearLayout>
Android代码(此代码未固定宽度和高度)
convertView = mInflater.inflate( R.layout.dialog_page, null );
convertView.setLayoutParams( new ListView.LayoutParams( 200, 300) );
Android代码(此代码我收到错误消息)
convertView = mInflater.inflate( R.layout.lock_file_page, parent );
convertView.setLayoutParams( new ListView.LayoutParams( 200, 300) );
错误消息
java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView
如何在运行时修复宽度和高度。
提前致谢。
答案 0 :(得分:26)
尝试此代码..
LayoutParams lp = (LayoutParams) mListView.getLayoutParams();
lp.height = 300;
mListView.setLayoutParams(lp);
答案 1 :(得分:1)
首先删除LayoutParams的导入文件,然后使用以下代码替换LayoutParams。
LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(200, 300);
convertView.setLayoutParams(params);
答案 2 :(得分:0)
试试这个
public void setDynamicHeight(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
if(listItem != null){
listItem.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
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();}