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)?
Asked
Active
Viewed 1,975 times
2 Answers
12
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
}

Dave
- 6,064
- 4
- 31
- 38
-
1Of course, thank you! Both answers are correct and written on the exact time, so I'm going to approve your answer as the right one (less reputation than @alextsc) and up vote alextsc answer. – Indrek Kõue Aug 26 '11 at 12:31
7
Sure, create a base activity and write your code in there.
public class MenuActivity extends Activity {
// Menu stuff goes here
}
Then extend your seperate activities from that.
public class MyActivity1 extends MenuActivity { ... }
public class MyActivity2 extends MenuActivity { ... }
public class MyActivity3 extends MenuActivity { ... }
-
1I can't accept two answers as correct ones so I'm just going to up vote yours. – Indrek Kõue Aug 26 '11 at 12:32
-
1No problem, we posted at the same time. I think Dave gave the better one here anyway (more details), so accept his answer. :) – Aug 26 '11 at 12:34