我是这样解决的:
在setOnNavigationItemSelectedListener 里,也就是每次点击底部导航栏时,判断一下点击的是否是当前界面的导航栏,否才发生跳转。
public class MainActivity extends AppCompatActivity {
int checked = 1;//当前显示的界面,共有1,2,3三个
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@SuppressLint("ResourceAsColor")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//去掉标题栏
getSupportActionBar().hide();
getWindow().setStatusBarColor(this.getResources().getColor(R.color.background));
setContentView(R.layout.activity_main);
//设置导航栏
final BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
final NavController controller = Navigation.findNavController(this, R.id.fragment_up);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.taskFragment:
if (checked != 1) {//判断点击的界面是不是当前界面,不是才发生跳转
controller.popBackStack();
controller.navigate(R.id.taskFragment);
checked = 1;
}
break;
case R.id.goalFragment:
if (checked != 2) {
controller.popBackStack();
controller.navigate(R.id.goalFragment);
checked = 2;
}
break;
case R.id.notesFragment:
if (checked != 3) {
controller.popBackStack();
controller.navigate(R.id.notesFragment);
checked = 3;
}
break;
}
return true;
}
});
}
}