Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple activities, identical onCreateOptionsMenu, onOptionsItemSelected and onKeyDown. Can I somehow reuse the code?

Multiple activities have identical onCreateOptionsMenu, onOptionsItemSelected and onKeyDown. When I implement a change, I have to do it in every activity (work time * activity count). Is there a way to reuse the code (for example write all of the three methods in one place and put down a reference to it in every activity)?

like image 769
Indrek Kõue Avatar asked Aug 26 '11 12:08

Indrek Kõue


1 Answers

Sure, just create your own Activity class that all your classes inherit from.

A bit like this - create an abstract base class that inherits from Activity and implements common behaviour:

public abstract class MyBaseActivity extends Activity {
    public Menu onCreateOptionsMenu(Menu menu) {
        /* do common menu stuff */
    }
}

Then make your individual activities inherit from your base class:

public class MyActivity extends MyBaseActivity {
    // inherits behaviour from MyBaseActivity
    // so don't need to re-implement onCreateOptionsMenu
}
like image 102
Dave Avatar answered Sep 28 '22 12:09

Dave