How to "extend" the PreferenceActivity class in Android with my "base" class?

the situation is this: I use "BaseClass" with some standard functions (for example, a standard menu generator), and all other actions "expand" it to get the same menu and other things:

public class Base extends Activity { //some stuff } 

then

 public class MainActivity extends Base { //some other stuff } public class AdditionalActivity extends Base { //some other stuff x2 } // etc. 

The problem arises when I need the same functions in the Preferences activity, when the class should "extend" PreferenceActivity, and not the standard one. How do I deal with this? Ive read about the "implements vs extends" behavior and the like, but Im not very experienced at OOP to handle this and find a better solution. C & P-ing from the Base to Prefs class, which extends PreferenceActivity, seems to solve the problem, but it is by far the worst solution.

Thanks in advance for your help!

+4
source share
2 answers

You might want to create a PreferenceBaseActivity class that extends PreferencesActivity . Here you have several options:

  • Or override the same methods from BaseActivity (not optimal).
  • Extract the methods from BaseActivity into the ActivityHelper class, and your BaseActivity and your PreferencesBaseActivity contain helper links. This way you can delegate your work from your core activity to an ActivityHelper .
+3
source

Consider putting your reusable methods in a helper class and adding an instance to both Base and Prefs :

 public class Base extends Activity { // same with Prefs private Helper helper; public Base() { // .. super calls, etc this.helper = new Helper(this); } } 

 public class Helper { private Activity parent; public Helper(Activity parent) { this.parent = parent; } // your methods. If you need to call methods from Activity, use // the parent reference } 
+1
source

All Articles