android - 如何在 Android 中创建下拉复选框列表?
问题描述
我想使用 Kotlin 为我的 Android 应用程序创建一个材料设计公开的下拉菜单,但我希望下拉菜单是一个复选框列表,然后我可以在其中检索用户以编程方式选择的复选框。
我该怎么做呢?是否有一个已经存在的库来执行此操作?
解决方案
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;
}
});
}
});
}
推荐阅读
- webpack - 请帮助向此配置添加规则和插件
- reactjs - 在 react i18next 的 t() 中指定键:值
- c# - 如何填充嵌套的 json 对象 C#
- python - 带有 Firebase 的 Flask-RESTful 随机返回 Null
- python - 必须首先安装什么才能使 instapy 正常运行?
- amazon-ec2 - 将域从 Bluehost 迁移到 AWS
- amazon-web-services - sagemaker 中实时预测中的特征提取
- angular - AG-Grid 自定义过滤器 (Angular) - 如何在 OnNewRowsLoaded() 中获取行数据
- java - 在数组中交换随机选择的位置
- python - AWS CDK 在部署 s3 对象时给出了意外的关键字参数“follow_symlinks”