开发者

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?


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
    }
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜