shkschneider
shkschneider

Reputation: 18243

How to share methods across multiple Android activities types

I'm building and Android application using ActionBarSherlock.

I have multipe types of activities:

I want all my activities to share common methods to follow an internal workflow of screens.

If I create a Workflow class that extends SherlockFragmentActivity then my MapActivity does not work anymore. If I create a Worflow class that extends SherlockMapActivity then my TutorialActivity does not work anymore (because it's using a new SectionsPagerAdapter(getSupportFragmentManager());.

Do note that the common methods I want are also running startActivity().

I know Java cannot have a class that extends more than one class, so how should I go about this?

public class Workflow extends SherlockMapActivity {

protected void goMain() {
    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent);
}

@Override
protected boolean isRouteDisplayed() {
    return false;
}

    // ...
}

public class TutorialActivity extends Workflow {
    // ...
    // new SectionsPagerAdapter(getSupportFragmentManager());
    // ...
}

public class GameActivity extends Workflow {
    // ...
    // MapView
    // ...
}

I also want to share code like this:

@Override
protected void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setProgressBarIndeterminate(true);
    setProgressBarIndeterminateVisibility(false);
}

Upvotes: 1

Views: 1769

Answers (1)

Adam Arold
Adam Arold

Reputation: 30528

You can create a custom Activity class and extend that in your activities.

So for example:

public abstract class DerivedActivityA extends Activity implements CustomInterfaceA {

    // ... your code here
}

public abstract class DerivedActivityB extends DerivedActivityA implements CustomInterfaceB {

    // ... your code here
}

If you have to implement multiple interfaces then use abstract classes like I did above and implement interfaces.

Edit: If I get it right SectionsPagerAdapter is just an adapter so you can compose it in one of your classes as a field.

Edit2: You can't extend two classes and you can't compose an Activity into another one so you either have to write things for yourself or extract the functionality you need from your third party library.

Upvotes: 3

Related Questions