android如何创建我自己的Activity并扩展它? [英] android how to create my own Activity and extend it?

查看:27
本文介绍了android如何创建我自己的Activity并扩展它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个扩展 Activity 的基类,它在我的应用程序中执行一些常见任务并从中扩展我的 活动,格式如下:

I need to create a base class that extends Activity which does some common tasks in my application and extend my activities from it,in the following form:

公共 BaseActivity 扩展了 Activity{....}

public SubActivity 扩展 BaseActivity{...}

SubActivity中我需要给BaseActivity中定义的一些变量和UI组件赋值,我可能需要为SubActivity定义不同的布局> 根据一些标志值,也(在 SubActivity 中)我想执行在 BaseActivity 中定义的 asyncTask.

in SubActivity I need to give values to some variables and UI components defined in BaseActivity, I may need to define a different layout for SubActivity according to some flag value, also(in SubActivity ) I want to execute asyncTask that is defined in BaseActivity.

这可能吗?如果是的话,是否有任何可能有帮助的教程?提前致谢

is this possible? if yes, is there any tutorial that may help? thank you in advance

推荐答案

你到底想达到什么目的?除了一些变量或部分布局之外,有两个不同的活动具有相同的用户界面?

What exactly are you trying to achieve? Having two different activities with a common ui, except for some variables or parts of the layout?

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

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) {
        super.onCreate(bundle);
        setContentView(getLayoutResourceId());
    }

    protected abstract int getLayoutResourceId();
}

public class Activity1 extends BaseActivity {
    @Override
    public void onCreate(bundle) {
        super.onCreate(bundle);
        // 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.

这篇关于android如何创建我自己的Activity并扩展它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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