Cyker
Cyker

Reputation: 10904

How to extend multiple Android activities

Say someone wants an Activity which both has an action bar and a preference, the first idea in mind is probably

public class MyActivity extends ActionBarActivity, PreferenceActivity

But Java doesn't allow this. I know API 11+ Activities has actionbar builtin. It's just an example of wondering how to use multiple features from multiple base classes.

EDIT: Based on the feedback it seems we have to hack in this case. IMHO it could be as simple as putting all activity utilities as fields in class Activity and implement getter/setter to use those utilities. Well, in reality, it isn't.

Upvotes: 0

Views: 6899

Answers (4)

Smalls
Smalls

Reputation: 374

You can create a subclass of the PreferenceActivity, called AppCompatPreferenceActivity (or whatever you would like), to use an AppCompatDelegate to provide the SupportActionBar functionality. You can then subclass the new AppCompatPreferenceActivity for your MyActivity class like so:

public class MyActivity extends AppCompatPreferenceActivity

For how to do this, check out the AppCompatPreferenceActivity sample code from the Chromium project.

Upvotes: 0

Squonk
Squonk

Reputation: 48871

As mentioned in the other answers, Java doesn't allow multiple inheritance.

If you want an ActionBar as well as something such as Preference functionality, consider using a PreferenceFragment

It's not quite the same as multiple inheritance but Fragments allow adding extra functionality to Activities.

Upvotes: 0

auracool
auracool

Reputation: 172

simple solution:

  • Firstly you can't extend multiple classes..java does not support multiple inheritance see here
  • Secondly using action bar sherlock library here, this gives you action bar functionality without extending the actionbaractivity plus its backwards compatiable.

Or...you can implement a custom action bar go here

Upvotes: 0

MrEngineer13
MrEngineer13

Reputation: 38856

No you cannot extend from two classes in Java. Typically in Android to add the ActionBar to the older PreferenceActivity there are a couple of hacks you can do or libraries that also do the same thing. However, recently with the new AppCompat library they introduced the Toolbar widget which can be used to add an Actionbar to your PreferenceActivity in this case. For more information, checkout this post I recently wrote on how to add a Toolbar to your legacy SettingsActivity.

Upvotes: 1

Related Questions