检查和取消选中抽屉菜单中的项目

时间:2017-11-21 12:32:50

标签: java android xml android-navigation-drawer

我有一个包含菜单的抽屉布局,我已将第一个菜单项设置为mainActivity.java文件中的默认选定菜单项。在这样做之后,我使用名为previousItem的int变量编写了一些代码,以便能够将先前检查的菜单项作为已检查项删除,并将新选择的菜单项设置为选中的菜单项。但是,我继续获得IndexOutOfBounds异常,我不知道如何找到解决此问题的方法。我发布了我的mainActivity.java文件和日志:

public class MainActivity extends AppCompatActivity {

int previousItem;

// Declaring our dialog
ImportantDialogFragment dialogFragment = new ImportantDialogFragment();

GridView gridView;

// NavMenu member vars
private DrawerLayout mDrawerLayout;
private NavigationView navigationView;
private ActionBarDrawerToggle mToggle; // Button for toggling the side menu

private Toolbar mToolbar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Showing the disclaimer dialog every time the app starts
    dialogFragment.show(getSupportFragmentManager(),"IMPORTANT_NOTICE");

    // Get Screen Size Details
    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    int height = displayMetrics.heightPixels;
    final int width = displayMetrics.widthPixels;

    gridView = (GridView) findViewById(R.id.gridViewLayout);
    gridView.setAdapter(new ImageAdapter(this)); // used to set the contents of the GridView-in this case images-

    // When an item from the GridView gets clicked
    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // Create a new Intent...
            Toast.makeText(MainActivity.this, "Position: " + position, Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(MainActivity.this,CardViewActivity.class);
            intent.putExtra("Card Index",position);
            intent.putExtra("SCREEN_WIDTH",width);
            startActivity(intent);
        }
    });

    mToolbar = (Toolbar) findViewById(R.id.navActionBar);
    setSupportActionBar(mToolbar); // check quick doq
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    mToolbar.setTitle("");
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.drawer_open,R.string.drawer_closed); // Instantiating our button

    navigationView = (NavigationView) findViewById(R.id.nav_view);

    // Sets the default selected menu item, to the Home item
    navigationView.getMenu().findItem(R.id.nav_home).setChecked(true);
    previousItem = navigationView.getMenu().getItem(0).getItemId();

    // When an item inside the NavView gets clicked, then handle the event...
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {
                case R.id.nav_home:
                    mDrawerLayout.closeDrawer(Gravity.START);
                    break;
                case R.id.nav_UserBoxGLB:
                    // USERBOX GLB ACTIVITY
                    Intent userBoxGLBintent = new Intent(MainActivity.this,UserBoxGLBActivity.class);
                    startActivity(userBoxGLBintent);
                    break;
                case R.id.nav_UserBoxJP:
                    break;
                case R.id.nav_settings:
                    break;
                case R.id.nav_feedback:
                    break;
                case R.id.nav_contact_us:
                    break;
                case R.id.nav_donate:
                    // Open the website's URL in a browser window
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.addCategory(Intent.CATEGORY_BROWSABLE);
                    intent.setData(Uri.parse("http://www.google.com"));
                    startActivity(intent);
                    break;
                case R.id.nav_about:
                    break;
                default:
                    return onNavigationItemSelected(item);
            }
            navigationView.getMenu().getItem(previousItem).setChecked(false);
            item.setChecked(true);
            previousItem = navigationView.getMenu().findItem(item.getItemId()).getItemId();
            mDrawerLayout.closeDrawers();
            return false;
        }
    });

    mDrawerLayout.addDrawerListener(mToggle);
    mToggle.syncState();
}



// When an item from the Action Bar gets tapped, then...
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if(mToggle.onOptionsItemSelected(item)) {
        return true;
    }
    return onOptionsItemSelected(item);
}
}

例外:

11-21 14:27:45.553 19074-19074/com.dcv.spdesigns.dokkancards E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.dcv.spdesigns.dokkancards, PID: 19074
                                                                           java.lang.IndexOutOfBoundsException: Index: 2131230840, Size: 5
                                                                               at java.util.ArrayList.get(ArrayList.java:411)
                                                                               at android.support.v7.view.menu.MenuBuilder.getItem(MenuBuilder.java:741)
                                                                               at com.dcv.spdesigns.dokkancards.MainActivity$2.onNavigationItemSelected(MainActivity.java:122)
                                                                               at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:154)
                                                                               at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
                                                                               at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
                                                                               at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
                                                                               at android.support.design.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:342)
                                                                               at android.view.View.performClick(View.java:6261)
                                                                               at android.view.View$PerformClick.run(View.java:23748)
                                                                               at android.os.Handler.handleCallback(Handler.java:751)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                               at android.os.Looper.loop(Looper.java:154)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

1 个答案:

答案 0 :(得分:0)

您正在使用项目ID而不是菜单中的项目位置。 您可以使用以下代码行找到菜单项的位置:int position=items.indexOf(menuItem);

在您的代码中:

final List<MenuItem> items=new ArrayList<>();
for(int i=0; i<menu.size(); i++){
    items.add(menu.getItem(i));
}
...
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        ...
        navigationView.getMenu().getItem(previousItem).setChecked(false);
        item.setChecked(true);
        previousItem = items.indexOf(navigationView.getMenu().findItem(item.getItemId()));
...
}

Reference