当前位置:  开发笔记 > 编程语言 > 正文

Android NavigationView设置默认片段

如何解决《AndroidNavigationView设置默认片段》经验,为你挑选了1个好方法。



1> 小智..:

首先在onCreate方法中获取菜单项:

        //Get menuItem index 0
        if (savedInstanceState == null) {
              MenuItem item =  navigationView.getMenu().getItem(0);
              onNavigationItemSelected(item);
        }

并在onNavigationItemSelected:

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();
    Fragment fragment = null;
    switch (id) {
        case R.id.nav_capture_credentials:
            fragment = new TestFragment();
            break;
        case R.id.nav_pending_credentials:
            fragment = new TestOtehrFragment();
            break;
        case R.id.nav_close_session:
            //Logout
            break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, fragment).commit();
        //Set menuItem checked and title 
        item.setChecked(true);
        setTitle(item.getTitle());
        //close navigation view
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    } else {
        Log.e(TAG, "Error to create a fragment");
    }
    return false;
}

推荐阅读
云聪京初瑞子_617
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有