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

后端 未结 2 1663
夕颜
夕颜 2021-02-06 06:23

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 redund

2条回答
  •  伪装坚强ぢ
    2021-02-06 06:56

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

提交回复
热议问题