这是我的代码:
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the BottomNavigationView
bottomNavigationView = findViewById(R.id.bottom_navigator);
// Set the selected item
bottomNavigationView.setSelectedItemId(R.id.actiom_home);
// Set the listener for BottomNavigationView
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.action_dashboard: // Use direct resource ID
Log.d("SwitchCase", "Dashboard selected");
startActivity(new Intent(getApplicationContext(), Dashboard.class));
overridePendingTransition(0,0);
return true;
case R.id.actiom_home: // Use direct resource ID
Log.d("SwitchCase", "Home selected");
return true;
case R.id.about: // Use direct resource ID
Log.d("SwitchCase", "About selected");
startActivity(new Intent(getApplicationContext(), About.class));
overridePendingTransition(0,0);
return true;
default:
Log.d("SwitchCase", "Default case");
return false;
}
}
});
}
}
如果有任何冲突,我尝试更改ID。
不能在 switch case 语句中使用 ids,因为 ids 是非常量表达式 而且 switch 只接受 Constant 表达式,我建议你使用 if else-if 或 just if 来代替
示例-
int id = item.getItemId();
if (id == R.id.menu_incomplete_orders){
startActivity(new Intent(MainActivity.this, MainActivity_Recent_orders.class));
}
if (id == R.id.menu_showcase_products) {
startActivity(new Intent(MainActivity.this, MainActivity_showcase_products.class));
}