Create a separate class and instantiate it by passing this
Example
Mainactivity.class - contains onCreate and cia methods
Meumenu.class - contains the creation method
In the onCreate method of Mainactivity Voce calls the Meumenu meuMenu = new Meumenu(this); and then meuMenu.criaMenu();
In the Meumenu class, you receive the this parameter, which will be the Activity type...which is probably Activity or Appcompatactivity...
To be able to access the Mainactivity methods in Meumenu, for example findViewById, you will need to call this parameter you received (from the Activity or Appcompatactivity type)...example parametro.findViewById(R.id.menu);
Then, all Activity that needs this menu is just to call Meumenu meuMenu = new Meumenu(this); and then meuMenu.criaMenu(); 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
}
Meumenu.class
Activity activity;
Button button;
public MeuMenu(Activity activity){
this.activity = activity;
}
public void criaMenu(int id){
button = (Button) activity.findViewByid(id);
button.setOnClickListener...
}
By the way, you can use this pattern to better organize the code by removing all buttons and events from activities and moving to a separate class...
Create a first Activity with the repeating code. When you want a new Activity to use this code, make it inherit from the first.
– ramaral
how can I do this? using extends?
– Gustavo Paes
Yes, using
extends
.– ramaral