安全传递一个活动的实例到另一个对象? [英] Safe to pass instance of an Activity to another object?

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

问题描述

什么我基本上试图做的是通过我的活动的实例,将构建动态用户界面的另一个对象。

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

主要的原因,我这样做是为了保持活动类的清洁。

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);

我要保持活动中的动态视图建筑,或者是正常的传递实例其他类做到这一点?

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

如果我把它的活动,它只是感觉臃肿我,更难管理。

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

推荐答案

在我看来,这不是一个好主意,通过活动的地方 - 其实我不知道这是否会做任何事情

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 - 你可以创建自己的类,扩展视图类,创建用户界面那里。 你有什么要传递给这个类是你的活动范围内!

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.

希望它会工作!

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

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