简体   繁体   English

更新导航抽屉中当前突出显示的片段

[英]Update currently highlighted fragment in nav drawer

When I open a new fragment from the nav drawer it correctly highlights it but when I press the back button it doesn't update the highlighted element so I was thinking of using navigationView.setCheckedItem(); 当我从导航抽屉中打开一个新片段时,它会正确地突出显示它,但是当我按下“后退”按钮时,它不会更新突出显示的元素,因此我在考虑使用navigationView.setCheckedItem(); but that needs an int and I have no clue on what to put there since I have no idea if I can use the back stack somehow or not. 但这需要一个int值,而且我不知道该放在哪里,因为我不知道是否可以某种方式使用back stack。

At the moment onBackPressed only has 目前,onBackPressed仅具有

    public void onBackPressed() {
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    }else{
        super.onBackPressed();
    }
}

What am I doing wrong? 我究竟做错了什么?

EDIT: I solved by doing one of the worst things I could have imagined, in each fragment : 编辑:我通过在每个片段中做我想不到的最糟糕的事情之一来解决:

@Override
public void onResume() {
    super.onResume();
    auIsInFront = true;
}

@Override
public void onPause() {
    super.onPause();
    auIsInFront = false;
}

And then in MainActivity : 然后在MainActivity中

@Override
public void onBackPressed() {
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    }else{
        super.onBackPressed();
        NavigationView navigationView = findViewById(R.id.nav_view);
        if (isInFront){
            navigationView.setCheckedItem(R.id.nav_home);
        }else if (standardIsInFront){
            navigationView.setCheckedItem(R.id.nav_standard);
        }else if (auIsInFront){
            navigationView.setCheckedItem(R.id.nav_au);
        }
    }
}

I know it's horrible but that's the only thing that I could think of 我知道这很可怕,但这是我唯一能想到的

As the documentation says setCheckedItem takes view id as argument. 正如文档所述 ,setCheckedItem将视图id作为参数。 You should use it like this: 您应该这样使用它:

navigationView.setCheckedItem(R.id.yourMenuItem);

Now You want to create some variable that keeps last activity / menu item and then change highlith. 现在,您想创建一些保留上一个活动/菜单项的变量,然后更改highlith。 Example: 例:

int lastMenuID;
public void onBackPressed() {
  DrawerLayout drawer = findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
      drawer.closeDrawer(GravityCompat.START);
    }else{
      int thisID = /*[this menu item]*/;
      navigationView.setCheckedItem(lastMenuID);
      lastMenuID = thisID;
      super.onBackPressed();
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM