我有一个导航抽屉,由3组组成。 当我从另一个组中选择一个项目时,前一个组中的项目仍然被标记为已检查,即使我有代码将其设置为未选中(并且从调试器我知道已到达代码)。 如何确保单个选择项目?
drawer.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:id="@+id/first_group"
android:checkableBehavior="single">
<item
android:id="@+id/my_trips"
android:checked="true"
android:icon="@drawable/ic_trips"
android:title="@string/menu_my_trips" />
<item
android:id="@+id/interactive_demo"
android:icon="@drawable/ic_demo"
android:title="@string/menu_interactive_demo" />
<item
android:id="@+id/email_support"
android:icon="@drawable/ic_support"
android:title="@string/menu_email_support" />
</group>
<group
android:id="@+id/second_group"
android:checkableBehavior="single">
<item
android:id="@+id/faq"
android:icon="@drawable/ic_action_help"
android:title="@string/menu_faq" />
<item
android:id="@+id/user_agreement"
android:icon="@drawable/ic_action_description"
android:title="@string/menu_user_agreement" />
</group>
<group
android:id="@+id/third_group"
android:checkableBehavior="single">
<item
android:id="@+id/logout"
android:icon="@drawable/ic_action_input"
android:title="@string/menu_logout" />
</group>
main_activity.java
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
FragmentManager fragmentManager = getSupportFragmentManager();
int numOfItems = navigationView.getMenu().size();
for (int i = 0; i < numOfItems; ++i){
MenuItem currentItem = navigationView.getMenu().getItem(i);
if (currentItem.isChecked())
currentItem.setChecked(false);
}
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
switch (menuItem.getItemId()) {
case R.id.my_trips:
...
答案 0 :(得分:0)
解决方案:将其他组设置为不可检查会带来所需的结果。
private void setMenuItemCheck(MenuItem menuItem){
int currentGroupId = menuItem.getGroupId();
ArrayList<Integer> allGroupsIds = new ArrayList<Integer>(){{
add(R.id.first_group);
add(R.id.second_group);
add(R.id.third_group);
}};
for (int i = 0; i < allGroupsIds.size(); ++i){
if (currentGroupId == allGroupsIds.get(i)) {
mNavigationView.getMenu().setGroupCheckable(allGroupsIds.get(i), true, true);
} else{
mNavigationView.getMenu().setGroupCheckable(allGroupsIds.get(i), false, true);
}
}
menuItem.setChecked(true);
}