我想将AlertDialog
设置为内部ListView
的长度,AlertDialog
底部有一个按钮,目前即使列表包含 1 或 2 个项目,也跨越整个屏幕,我怎么能做到这一点,
这是我到目前为止的代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/lvItemsSelected"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="@+id/buttonOk"/>
<Button
android:id="@+id/buttonOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:text="OK"/>
</RelativeLayout>
如果这可以帮助您,请尝试在将数据填充到 ListView 后调用此方法
public void getListViewSize(ListView myListView, Context context) {
ListAdapter myListAdapter = myListView.getAdapter();
if (myListAdapter == null) {
return;
}
int totalHeight = 0;
for (int size = 0; size < myListAdapter.getCount(); size++) {
View listItem = myListAdapter.getView(size, null, myListView);
if (listItem instanceof ViewGroup)
listItem.setLayoutParams(new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
@SuppressWarnings("deprecation")
int screenWidth = display.getWidth();
int listViewWidth = screenWidth - 65;
int widthSpec = View.MeasureSpec.makeMeasureSpec(listViewWidth,
View.MeasureSpec.AT_MOST);
listItem.measure(widthSpec, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = myListView.getLayoutParams();
params.height = totalHeight
+ (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
myListView.setLayoutParams(params);
myListView.requestLayout();
}
你可以做的是使用ConstraintLayout
而不是RelativeLayout
,然后将AlertDialog
的约束链接到ListView
的宽度