【问题标题】:Navigation Drawer: change selected item after replace another fragment导航抽屉:替换另一个片段后更改所选项目
【发布时间】:2016-12-02 13:44:22
【问题描述】:

我正在使用 android 默认导航抽屉活动。假设我有片段A和片段B,片段A中有一个按钮,单击按钮后它将从片段A重定向(替换)到B。 但是导航抽屉中的选定项仍然突出显示片段A。有什么方法可以更改它以突出显示片段B而不是A?

@覆盖 public void onClick(View v) {

    if(carplate.getText().toString().equals("")){Toast.makeText(getActivity(),"Please enter your car plate number",Toast.LENGTH_SHORT).show();}
    else{
    Status status = new Status();
    FragmentManager fragmentManager = getFragmentManager();
    android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.content_frame,status);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
    }
}

这个函数在片段A下。I need the selected item automatic change to fragment B(Status) after i pressed the button in fragment A.

【问题讨论】:

  • 你能贴一些代码吗?
  • 已编辑。那样行吗?或者你需要其他指定的代码?

标签: android-studio


【解决方案1】:

是的,这很容易 首先,您必须获取导航视图,然后根据从 0 开始的项目索引从导航视图和高亮/显示选择中获取菜单。将以下代码行放在 onclick 方法中。

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.getMenu().getItem(0).setChecked(true);

如果您想打开片段,请使用以下代码行和指定的代码行

getSupportFragmentManager().beginTransaction()
     .replace(R.id.mainFragment,new yourNewFragment()).commit()

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多