如何在android中创建下拉复选框列表?

km0tfn4u  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(363)

我想使用kotlin为我的android应用程序创建一个material design exposed下拉菜单,但我希望下拉菜单是一个复选框列表,然后我可以通过编程检索用户选择的复选框。
我该怎么做?是否有一个已经存在的库来执行此操作?

uqxowvwt

uqxowvwt1#

您可以在中创建可检查菜单 res\menu 通过将项目 Package 成 <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;
                }
            });
        }
    });

}

相关问题