我试图在我的应用程序中使用来自
Android支持设计库的NavigationView.由于某些原因OnNavigationItemSelected监听器未被调用.这是我的代码
活动布局
<android.support.design.widget.NavigationView android:id="@+id/navigation_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" app:headerLayout="@layout/drawer_header" app:menu="@menu/drawer_menu" /> <FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" />
活动onCreate()
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutID()); toolbar = (Toolbar) findViewById(R.id.activity_toolbar); setSupportActionBar(toolbar); toolbar.inflateMenu(R.menu.common_menu); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp); actionBar.setDisplayHomeAsUpEnabled(true); } drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); navigationView = (NavigationView) findViewById(R.id.navigation_view); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(final MenuItem menuItem) { Snackbar.make(contentLayout,menuItem.getTitle() + " pressed",Snackbar.LENGTH_LONG).show(); menuItem.setChecked(true); // allow some time after closing the drawer before performing real navigation // so the user can see what is happening drawerLayout.closeDrawer(GravityCompat.START); mDrawerActionHandler.postDelayed(new Runnable() { @Override public void run() { navigate(menuItem.getItemId()); } },DRAWER_CLOSE_DELAY_MS); drawerLayout.closeDrawers(); return true; } }); usernameTextView = (TextView) findViewById(R.id.drawer_header_username); usernameTextView.setText(getAppDContext().getAccount().getUsername()); }
解决方法
当你做一个xml时,你应该在BaseLayout(FrameLayout,LinearLayout等)之后写下NavigationView
<DrawerLayout> <FrameLayout /> <NavigationView /> </DrawerLayout>