【发布时间】:2021-09-16 23:58:36
【问题描述】:
我有一个带有 ListView 的 alertDialog。默认情况下,它会显示它可以在对话框屏幕上显示的所有项目,但我想将其限制为一次 3 个项目。 我怎样才能做到这一点?这是我的代码的摘录,没有相关的部分被省略了
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER) || (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER)){
if (event.getAction() == KeyEvent.ACTION_UP){
ArrayList<HashMap<String, String>> names = new ArrayList<HashMap<String, String>>(totalItems);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
View rowList = getLayoutInflater().inflate(R.layout.activity_list, null);
ListView listView = rowList.findViewById(R.id.listView);
String[] from = new String[] { "title", "description" };
int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
int nativeLayout = R.layout.list_item;
SimpleAdapter simpleAdapter = new SimpleAdapter(this, names, nativeLayout , from, to);
listView.setAdapter(simpleAdapter);
simpleAdapter.notifyDataSetChanged();
alertDialog.setView(rowList);
listDialog = alertDialog.show();
这是列表视图布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorMenuBackground">
<ListView
android:id="@+id/listView"
android:listSelector="@color/colorMenuBackgroundSelected"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
【问题讨论】:
-
您可以通过给它一个固定的高度来限制布局中列表视图的大小,使其仅显示 3 个项目。而不是
android:layout_height="wrap_content",您可以输入如下内容:android:layout_height="144dp"假设一个列表视图项目的高度为 48dp。 -
如果您使用的是自定义适配器
public int getCount() { return 6; } -
@UsamaAltaf 我尝试覆盖方法 getCount,但它不再滚动列表。它似乎被困在返回的项目数量上。
-
你想要完整列表,但你想在滚动后在屏幕上显示 3 个项目,其他项目应该可见,那么这是不可能的
-
@BrunoBieri 有没有办法让它更灵活,不指定实际高度,只让它适合 3 件物品?
标签: android android-listview android-alertdialog simpleadapter