如果您正在使用BottomNavigationView,则应使用setOnNavigationItemSelectedListener()方法来设置选项卡的选择侦听器,而不是setOnItemSelectedListener()。这是因为setOnItemSelectedListener()方法是为Spinner控件设计的,而不是BottomNavigationView。以下是一个示例代码段:
//创建一个BottomNavigationView对象 BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
//设置选项卡的选择侦听器 bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.home: //处理home选项卡被选中的情况 return true; case R.id.dashboard: //处理dashboard选项卡被选中的情况 return true; case R.id.notifications: //处理notifications选项卡被选中的情况 return true; } return false; } });
//在此处添加其他需要的代码 //... //...