简体   繁体   中英

How do I “extend” PreferenceActivity class in Android with my “base” class?

the situation is like this: I am using "BaseClass" with some standard features (like standard menu generator) and all other activities "extend" it to get the same menu and other stuff:

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 want the same features in Preferences activity, when the class has to "extend" PreferenceActivity not the standard one. How do I better deal with that? Ive read about "implements vs extends" behavior and things like that but Im not quite experienced in OOP to deal with that and find the best solution. C&P-ing stuff from Base to Prefs class, which extends PreferenceActivity seems to solve the problem, but surely it`s the worst solution.

Thanks in advance for your assistance!

You will probably want to create a PreferenceBaseActivity class, which extends PreferencesActivity . From here, you have a couple options:

  1. Either reimplement the same methods from the BaseActivity (not optimal).
  2. Pull the methods from the BaseActivity into an ActivityHelper class, and have both your BaseActivity and your PreferencesBaseActivity contain references to the helper. This way you can delegate your work from your Base Activities to the ActivityHelper .

Consider putting your reuseable methods in a helper class and add 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM