android 如何在应用程序启动时选择导航抽屉中的第一项并打开片段

oogrdqng  于 2023-04-28  发布在  Android
关注(0)|答案(9)|浏览(345)

我用NavigationView创建了MainActivity。当打开Activity时,我想自动选择导航抽屉中的第一个项目,并在该项目下打开Fragment。我已经搜索了很多,但没有找到任何合适的解决方案。
做这件事的正确方法是什么?
Main Activity

public class MainActivity extends AppCompatActivity implements Config {

private NavigationView navigationView;
private DrawerLayout drawerLayout;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    toolbar.setTitleTextColor(getResources().getColor(R.color.colorIcons));

    if (null != getSupportActionBar())
        getSupportActionBar().setLogo(R.drawable.ic_blogger_white);

    //Start PostListFragmentWebView
    /*PostListFragmentWebView postListFragmentWebView = new PostListFragmentWebView();
    getSupportFragmentManager().beginTransaction()
            .replace(R.id.frame, postListFragmentWebView)
            .commit();*/

    //Initializing NavigationView
    navigationView = (NavigationView) findViewById(R.id.navigationView);

    //Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {

            //Checking if the item is in checked state or not, if not set it to checked state.
            if (menuItem.isChecked()) menuItem.setChecked(false);
            else menuItem.setChecked(true);

            //Closing drawer on item click
            drawerLayout.closeDrawers();

            //Check to see which item was clicked and perform the appropriate action.
            switch (menuItem.getItemId()) {

                case R.id.posts:
                    PostListFragmentWebView postListFragment = new PostListFragmentWebView();
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.frame, postListFragment)
                            .commit();
                    return true;

                case R.id.pages:
                    PageListFragmentWebView pagetListFragment = new PageListFragmentWebView();
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.frame, pagetListFragment)
                            .commit();
                    return true;

                case R.id.blog:
                    BlogInfoFragmentWebView blogInfoFragment = new BlogInfoFragmentWebView();
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.frame, blogInfoFragment)
                            .commit();
                    return true;

                default:
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.drawer_error), Toast.LENGTH_SHORT).show();
                    return true;

            }

        }
    });

    // Initializing Drawer Layout and ActionBarToggle
    drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open_drawer, R.string.close_drawer) {

        @Override
        public void onDrawerClosed(View drawerView) {
            // Code here will be triggered once the drawer closes as we don't want anything to happen so we leave this blank.
            super.onDrawerClosed(drawerView);
        }

        @Override
        public void onDrawerOpened(View drawerView) {
            // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank.

            super.onDrawerOpened(drawerView);
        }
    };

    //Setting the actionbarToggle to drawer layout
    drawerLayout.setDrawerListener(actionBarDrawerToggle);
    drawerLayout.getChildAt(0).setSelected(true);

    //calling sync state is necessary or else your hamburger icon wont show up
    actionBarDrawerToggle.syncState();
}
}
cgyqldqp

cgyqldqp1#

onCreate()中,以下代码将在第一次启动时加载第一个项目的片段:

if (savedInstanceState == null) {
    navigationView.getMenu().performIdentifierAction(R.id.posts, 0);
}

感谢calvinfly的这篇评论。

pexxcrt2

pexxcrt22#

android:checked="true"添加到第一个菜单项。
并手动选择一项,使用

getSupportFragmentManager().beginTransaction().replace(R.id.frame, postListFragment).commit();

打开碎片。

lbsnaicq

lbsnaicq3#

而不是普通的听众。。

navView.setNavigationItemSelected(new Navigation.View.OnNavigationItemSelectedListener() {bla, bla, bla})

将监听器创建为Obj:

NavigationView.OnNavigationItemSelectedListener navViewListener;
            navView.setNavigationItemSelectedListener(navViewListener = new NavigationView.OnNavigationItemSelectedListener() {bla, bla, bla})

...并使用Obj触发监听器事件:

navViewListener.onNavigationItemSelected(navView.getMenu().getItem(0));

...其中getItem(0)是第一个菜单项。
在其菜单项XML定义中使用方法getItem(0).setChecked(true)或android:checked=“true”。

rxztt3cl

rxztt3cl4#

你也可以在设置好navigationview之后使用navigationView.setCheckedItem(R.id.default)(javadoc)。

uxh89sit

uxh89sit5#

只需在onCreate方法中添加以下代码:

FragmentTransaction ftrans = getFragmentManager().beginTransaction();
ftrans.replace(R.id.container, <yourfragment>).commit();

为我工作!

d7v8vwbk

d7v8vwbk6#

考虑到方向和其他配置的变化,这可以做得更好。我们可以根据我们是否来自以前的状态来选择任何导航抽屉菜单项。检查:对于导航抽屉挥舞活动:-

public static final String SELECTED_NAV_MENU_KEY = "selected_nav_menu_key";
// The selected grid position
private int mSelectedNavMenuIndex = 0;

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

   ...........................................................

    navigationView.setNavigationItemSelectedListener(this);

    if (savedInstanceState != null) {
        // Recover assets
        mSelectedNavMenuIndex = savedInstanceState.getInt(SELECTED_NAV_MENU_KEY);

        // Recover menu as selected
        MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex);
        toggleNavMenuItemCheck(menuItem);
        navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
        return;
    } else {
        MenuItem menuItem = navigationView.getMenu().getItem(mSelectedNavMenuIndex);
        toggleNavMenuItemCheck(menuItem);
        navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);
    }
}

帮助取消选中或选中菜单项的切换方法

private void toggleNavMenuItemCheck(MenuItem menuItem) {
    if (menuItem.isChecked()){
        menuItem.setChecked(false);
    }  else {
        menuItem.setChecked(true);
    }
}

这是我保存所选菜单项状态的方式。选中:-

@Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id) {
            case R.id.nav_explore:
                showExploreFragment(null);
                mSelectedNavMenuIndex = 0;
                break;
            case R.id.nav_orders:
                mSelectedNavMenuIndex = 1;
                break;
            case R.id.nav_settings:
                mSelectedNavMenuIndex = 2;
                break;
            default:
                showExploreFragment(null);
                mSelectedNavMenuIndex = 0;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

// Save any important data for recovery
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(SELECTED_NAV_MENU_KEY, mSelectedNavMenuIndex);
    }
    • 注:代码行:**
navigationView.getMenu().performIdentifierAction(menuItem.getItemId(), mSelectedNavMenuIndex);

可以替换为代码:

onNavigationItemSelected(menuItem);
icomxhvb

icomxhvb7#

menu.xml中,请记住为单个项目指定android:checkable="true",为一组项目指定android:checkableBehavior="single"

<item
        android:id="@+id/pos_item_help"
        android:checkable="true"
        android:title="Help" />

    <group
        android:id="@+id/group"
        android:checkableBehavior="single">
        <item
            android:id="@+id/menu_nav_home"
            android:icon="@drawable/ic_home_black_24dp"
            android:title="@string/menu_nav_home" />
    </group>

然后在NavigationItemSelectedListener中使用setCheckedItem(R.id.item_id_in_menu)将其选中。

@Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {

            case R.id.pos_item_pos:
                navigationView.setCheckedItem(R.id.pos_item_pos);
                break;
            case R.id.pos_item_orders:
                navigationView.setCheckedItem(R.id.pos_item_orders);
                break;
            default:
        }
        return true;
    }

而且你不必再做管理所选项目的肮脏任务了。navigationView自己管理它。

dzjeubhm

dzjeubhm8#

1.)要初始化到HomeFragment,请在MainActivity中的onCreate()中使用以下命令:

Fragment fragment = new HomeFragment();
// replacing the fragment
if (fragment != null) {
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.commit();
}

2.)要在navigationDrawer中将项目设置为选中状态,请在navigation_menu.xml中将项目设置为选中状态

android:checked = "true"
xqnpmsa8

xqnpmsa89#

我觉得最好把

app:startDestination="@+id/nav_item"

选择第一个NavigationView。

相关问题