将 Activity 的实例传递给另一个对象是否安全? [英] Safe to pass instance of an Activity to another object?

查看:24
本文介绍了将 Activity 的实例传递给另一个对象是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上要做的是将我的 Activity 实例传递给另一个将构建动态 UI 的对象.

What I'm basically trying to do is pass an instance of my Activity to another object which will build the dynamic UI.

我这样做的主要原因是为了保持 Activity 类的干净.

The main reason I'm doing this is to keep the Activity class clean.

这样做有什么影响吗?会不会影响垃圾回收,导致内存泄漏?

Are there any repercussions when doing this? Will it affect the garbage collection and cause memory leaks?

这是我正在做的一个例子:

Here is an example of what I'm doing:

活动:

/* uses the instance of the Activity to build Views which are loaded from XML files (for non technical users to add content */
ContentHelper ch = new ContentHelper(MyActivity.this);

我应该将动态视图构建保留在 Activity 中,还是可以将实例传递给其他类来执行此操作?

Should I keep the dynamic View building within the Activity, or is it alright to pass the instance to other classes to do this?

如果我将它保留在 Activity 中,我只会觉得它很臃肿,而且更难管理.

If I keep it in the Activity, it just feels bloated to me and much harder to manage.

推荐答案

在我看来,将 ACTIVITY 传递到某个地方并不是一个好主意 - 实际上我不确定这是否会起到任何作用.

In my opinion it is not a good idea to pass the ACTIVITY somewhere - actually I'm not sure whether this will do anything at all.

你可以做的是:

1 - 您可以创建自己的类,扩展 View 类,在那里构建您的 UI.您必须传递给该类的是您的活动上下文!

1 - You can create your own class, extending View class, build your UI there. What you have to pass to that class is your activity context!

例如:

class Custom_UI_Builder extends View {
    public  Custom_UI_Builder(Context cxt) {
        super(cxt);
        // more stuff - your UI components...
    }
}   

在使用您的UI 类"的活动中

in the Activity that uses you 'UI class'

public myActivity extends Activity{
    @Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    myView = new Custom_UI_Builder(this);

            //what every else you need...

        mainLayout = new LinearLayout(this.getApplicationContext());
    mainLParam = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    mainLayout.setLayoutParams(mainLParam);
    mainLayout.setOrientation(LinearLayout.VERTICAL);
            mainLayout.addView(myView, LayoutParams.MATCH_PARENT, 390);
    setContentView(mainLayout);

}}

2 - 然后您可以在您的活动中创建 custom_UI_builder 类的实例.

2 - Then you can create an instance of your custom_UI_builder class in your Activity.

我不确定这是否会对内存负载产生任何不良影响.

I'm not sure if this will have any unwanted effects on memory load.

希望它会奏效!

这篇关于将 Activity 的实例传递给另一个对象是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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