How to reuse code from one Activity in another?

Asked

Viewed 462 times

1

I am creating an application in android studio in which I have a menu, I am using this menu in several activitys using "include", so in each Activity I need to rewrite the functions of the menu buttons, how I could make a separate method that works on all activitys?

  • 1

    Create a first Activity with the repeating code. When you want a new Activity to use this code, make it inherit from the first.

  • how can I do this? using extends?

  • Yes, using extends.

1 answer

1


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

  • Perfect Anderson, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.