首页 > 解决方案 > 如何在 Android 中创建下拉复选框列表?

问题描述

我想使用 Kotlin 为我的 Android 应用程序创建一个材料设计公开的下拉菜单,但我希望下拉菜单是一个复选框列表,然后我可以在其中检索用户以编程方式选择的复选框。

我该怎么做呢?是否有一个已经存在的库来执行此操作?

标签: androidmaterial-designandroid-menuandroid-checkboxpopupmenu

解决方案


res\menu您可以通过将项目包装到带有属性的<group>标签中来创建一个可检查的菜单:android:checkableBehavior="all"

poupup_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="all">
        <item
            android:id="@+id/one"
            android:title="One" />
        <item
            android:id="@+id/two"
            android:title="Two" />
        <item
            android:id="@+id/three"
            android:title="Three" />
    </group>

</menu>

然后以编程方式对其进行膨胀,并在数组中跟踪检查的项目:

boolean[] isChecked;
private PopupMenu mPopupMenu;


private void showPopupMenu() {

    // Button used to anchor the popup menu and to show it on its click
    final Button button = (Button) findViewById(R.id.button);

    if (mPopupMenu == null) {
        //Creating the instance of PopupMenu
        mPopupMenu = new PopupMenu(MainActivity.this, button);
        //Inflating the Popup using xml file
        mPopupMenu.getMenuInflater().inflate(R.menu.poupup_menu, mPopupMenu.getMenu());
        isChecked = new boolean[mPopupMenu.getMenu().size()];
    }

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            mPopupMenu.show();

            mPopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                public boolean onMenuItemClick(MenuItem item) {
                    int position = -1;
                    
                    if (item.getItemId() == R.id.one) position = 0;
                    else if (item.getItemId() == R.id.two) position = 1;
                    else if (item.getItemId() == R.id.three) position = 2;
                    
                    if (position != -1) {
                        isChecked[position] = !isChecked[position];
                        item.setChecked(isChecked[position]);
                    }

                    return true;
                }
            });
        }
    });

}

推荐阅读