How to reuse code from one activity to another?

1

I am creating an application in android studio where I have a menu, I am using this menu in several activities using "include", so in each activity I need to rewrite the functions of the menu buttons, how could I do a separate method that worked on all of the activity?

    
asked by anonymous 26.08.2016 / 01:13

1 answer

1

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 ...

    
26.08.2016 / 19:45