传递对象活动 [英] passing object to activity

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

问题描述

我可以初始化对象在我的第一个活动,你在它的所有活动???

Can i initialize object in my first activity and you it in all activity???

public class Calc{
    int x;
    int y;
    public Calc(int x, int y) {
       this.x = x;
       this.y = y;
    }
    public int sum() {
        return x + y;
    }
}
public class MainActivity extends Activity {

private int progressStatus = 0;
private Handler handler = new Handler();
private ProgressBar loading;
private static int progress;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    Calc c = new Calc(3, 4);
}
}


public class PreviewActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.preview);

            TextView txt = (TextView) findViewById(R.id.txt);
            txt.setText(Integer.toString(c.sum));
}
}

我怎么能初始化计算器对象MainActivity,并用它previewActivity。

How can i Initialize Calc object in MainActivity and use it PreviewActivity.

我怎样才能把它传递到另一个活动或我怎么能使其与其他活动分享

How can i pass it to another activity or how can i make it share with other activity

推荐答案

使用通过扩展,并编写自定义的应用程序类应用类,并保持你的对象,在这个类中,你需要在你的十字架活动

class MyApplication extends Application{
    Object a;

    public void setA(Object a){
         this.a = a;
    }

    public Object getA(){
         return a;
    }

}

现在让你一活动假定创建类的对象对象,并想用它在你的B活动。

Now lets suppose in your A activity you create object of class Object and want to use it in your B Activity.

做这种方式,

class ActivityA extends Activity(){

...
// some where in activity, set your object this way.
     Object aObj = new Object();
     ((MyApplication)getApplication()).setA(aObj);


...

}

class ActivityB extends Activity(){

...
// some where in activity, get your object this way.
     Object aObj = ((MyApplication)getApplication()).getA( );


...

}

您需要告诉你的的Andr​​oidManifest.xml 有关延长应用程序类。

You need to tell your androidManifest.xml about your extended Application class.

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

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