onNavigationItemSelected

onNavigationItemSelected

我想在应用程序启动时在导航抽屉中选择一个特定项目。
我在Visual Studio默认模板中添加了navigationView.SetCheckedItem(Resource.Id.nav_gallery);

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity_main);
        Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
        SetSupportActionBar(toolbar);

        FloatingActionButton fab = FindViewById<FloatingActionButton>(Resource.Id.fab);
        fab.Click += FabOnClick;

        DrawerLayout drawer = FindViewById<DrawerLayout>(Resource.Id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, Resource.String.navigation_drawer_open, Resource.String.navigation_drawer_close);
        drawer.AddDrawerListener(toggle);
        toggle.SyncState();

        var navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
        navigationView.SetNavigationItemSelectedListener(this);

        navigationView.SetCheckedItem(Resource.Id.nav_gallery);

    }


但是不会调用OnNavigationItemSelected

    public bool OnNavigationItemSelected(IMenuItem item)
    {
        int id = item.ItemId;

        if (id == Resource.Id.nav_camera)
        {
            // Handle the camera action
        }
        else if (id == Resource.Id.nav_gallery)
        {

        }


如果单击导航项,将调用OnNavigationItemSelected,一切正常。
选择默认项目的正确方法是什么?

更新

我添加了这一行解决了它。单击特定项目。

 navigationView.Menu.PerformIdentifierAction(Resource.Id.nav_gallery, 0);

最佳答案

  navigationView.getMenu().getItem(position).setChecked(true);


你可以创建一个功能

 public void selectDrawerItem(int position, String tag) {

    switch (position) {

        case 0:
            fragment = new DashboardFragment();
            tvToolbarTitleLand.setText("Dashboard");
            break;

         //code.................
    }

    if (fragment != null) {

        FragmentTransaction transaction = manager.beginTransaction();
        transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_right);
        transaction.replace(R.id.flMainContainer, fragment);
        transaction.addToBackStack(tag);
        transaction.commit();
    }

    navigationView.getMenu().getItem(position).setChecked(true);


}

让我知道您是否对此有任何疑问。

关于c# - NavigationView SetCheckedItem不会触发OnNavigationItemSelected,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56886264/

10-08 23:44