拥有基础活动课程是否很好? [英] Is it good to have a Base Activity class?

查看:50
本文介绍了拥有基础活动课程是否很好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

拥有BaseActivity类是否很好,它将作为所有其他活动的超类.我需要有一些通用的活动实现方式.

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.

BaseActivity:

public class BaseActivity extends Activity
{
     //All Common implementations goes here
}

活动

public class HomeActivity extends BaseActivity
{
}

推荐答案

在这种情况下,我建议您有一个基本的抽象活动以及两个具体的继承子类.您在基本活动中定义了所有常见行为,并为差异提供了抽象方法,然后在实际实现中将其覆盖.

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

这篇关于拥有基础活动课程是否很好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆