android – NavigationView OnNavigationItemSelectedListener未被调用

前端之家收集整理的这篇文章主要介绍了android – NavigationView OnNavigationItemSelectedListener未被调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在我的应用程序中使用来自 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>
原文链接:https://www.f2er.com/android/312765.html

猜你在找的Android相关文章