Create a separate class and instantiate it by passing this
Example
MainActivity.class - contains the onCreate and cia methods
MyMenu.class - contains the createMenu method
In the onCreate method of MainActivity you call MyMenu myMenu = new MyMenu (this); and then myMenu.createMenu ();
In the MyMenu class, you get the this parameter, which will be of the activity type ... that is probably Activity or AppCompatActivity ...
In order to access the MainActivity methods in MyMenu, such as findViewById, you need to call this parameter that you received (of type Activity or AppCompatActivity) ... example parameter.findViewById (R.id.menu); >
Then, every activity that needs this menu is just called MyMenu myMenu = new MeuMenu (this); and then myMenu.createMenu (); to create a menu ... Of course this menu should be in xml as well.
Example:
MainActivity.class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MeuMenu meuMenu = new MeuMenu(this);
meuMenu.criaMenu(R.id.btn); // id do xml
}
MyMenu.class
Activity activity;
Button button;
public MeuMenu(Activity activity){
this.activity = activity;
}
public void criaMenu(int id){
button = (Button) activity.findViewByid(id);
button.setOnClickListener...
}
Incidentally, you can use this pattern to better organize the code, removing all buttons and events from the activities, and moving to a separate class ...