I am attempting to create a menu bar that lives in all of my activities. To do this, I've extended AppCompatActivity
in AppMenu.java
file. The idea here is to call my custom AppMenu.getMenu(...)
method in every activity.
Unfortunately I can't figure out how to call getMenu
in my activities.
AppMenu.java:
public class AppMenu extends AppCompatActivity {
public void getMenu(BottomNavigationView bottomNavigationView, int selected) {
// Set Home selected
bottomNavigationView.setSelectedItemId(selected);
// Perform item selected listener
bottomNavigationView.setOnItemSelectedListener(new BottomNavigationView.OnItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch(item.getItemId())
{
case R.id.messages:
startActivity(new Intent(getApplicationContext(), dm.class));
overridePendingTransition(0,0);
return true;
case R.id.home:
return true;
case R.id.profile:
startActivity(new Intent(getApplicationContext(), userProfile.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// How can I call getMenu?
AppMenu m = new AppMenu(); // Can not resolve this
getMenu(); // Can not resolve this either
}
}
For additional context, I am following this GeeksForGeeks article but I do not think it's a great idea to repeat the same menu code in every activity.
CodePudding user response:
All you have to do is instead of extend AppCompatActivity, extend your AppMenu (I would say this should be called BaseMenuActivity), it would be like this:
public class MainActivity extends AppMenu {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getMenu()
}
}