Home » Android » How do I create common code for parts of Android activities?

How do I create common code for parts of Android activities?

Posted by: admin June 15, 2020 Leave a comment

Questions:

In my application there are 14 activities. Out of that 9 activity contains custom title bar and tab pane. so here I need to write this common code at one place instead of redundant code in each activity that contain custom title bar and tab pane code (i.e layout and it’s activity specific code)

What are the possible ways to do this?

How to&Answers:

The common way is:

  • Create a super class called, for instance, CommonActivity which extends Activity
  • Put the boilerplate code inside that class
  • Then make your activities extend CommonActivity instead of Activity:

Here a simple example:

public class CommonActivity extends Activity{
    public void onCreate(Bundle b){
        super.onCreate(b);
        // code that is repeated
    }

    protected void moreRepeatitiveCode(){
    }
}

And your current activities:

public class AnActivity extends CommonActivity{
    public void onCreate(Bundle b){
        super.onCreate(b);
        // specific code
    }
}

Answer:

Hmm.. Common code doesn’t always need to be in Activity class but just regular class. Than we could call those methods according to our needs referring to the common code class.

Am I right with this example?

Of course in case we need it like Activity, above proposal would work perfectly if we take care of Activity lifecycle and we don’t forget to add it to manifest file.

In general Activities should just create UI, handle events occurrences and delegate business logic and/or other actions to the other components in our App.

Cheers