Is it good to have a Base Activity class?

后端 未结 3 1988
情歌与酒
情歌与酒 2021-02-02 03:07

Is it good to have BaseActivity class and that will act as super class for all other activity. I need this to have some common implementations for the activities.

3条回答
  •  死守一世寂寞
    2021-02-02 03:51

    In this case, I suggest having a base abstract activity, and two concrete inherited subclasses. You define all the common behaviour in the base activity, and have abstract methods for the differences, which you then override in your actual implementations.

    For example, for two activities with different layout resources:

    public abstract class BaseActivity extends Activity { 
        @Override
        public void onCreate(Bundle savedInstanceState) { 
            super.onCreate(savedInstanceState);
            setContentView(getLayoutResourceId()); 
        } 
        protected abstract int getLayoutResourceId(); 
    } 
    
    
    
    public class Activity1 extends BaseActivity { 
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState); // do extra stuff on your resources, using findViewById on your layout_for_activity1 
        } 
         @Override
        protected int getLayoutResourceId(){ 
            return R.layout.layout_for_activity1;
        } 
    }
    

    You can have a lot more abstract methods, for every bit you want specific to your subclasses.

    Doing that is, in my opinion, a lot better than having a concrete subclass to a concrete superclass: that can lead to many problems and is usually difficult to debug.

    Happy coding. Let me know need more help!!

提交回复
热议问题