Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 344
Vicky Avatar asked Feb 01 '11 18:02

Vicky


2 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
    }
}
like image 112
Cristian Avatar answered Sep 28 '22 10:09

Cristian


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

like image 38
Ewoks Avatar answered Sep 28 '22 09:09

Ewoks