将对象传递给活动

时间:2012-07-04 16:09:40

标签: android

我可以在第一个活动中初始化对象吗?你可以在所有活动中初始化对象???

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中初始化Calc对象并使用它PreviewActivity。

如何将其传递给其他活动或如何与其他活动共享

3 个答案:

答案 0 :(得分:2)

制作

public class Calc implements Serializable {
int x;
int y;
public Calc(int x, int y) {
   this.x = x;
   this.y = y;
}
public int sum() {
    return x + y;
}

}

启动PreviewActivity时

Intent intent = new Intent(mContext, PreviewActivity .class);
intent.putParcelableArrayListExtra("data",c);
startActivity(intent);

并在您的PreviewActivity中 这样做

Calc c=(Calc ) getIntent().getSerializableExtra("data");

答案 1 :(得分:2)

通过扩展和编写自定义Application课程来使用Application课程,并将您的对象保留在十字架所需的课程中Activities

class MyApplication extends Application{
    Object a;

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

    public Object getA(){
         return a;
    }

}

现在让我们假设您在A活动中创建了类Object的对象,并希望在您的B活动中使用它。

这样做,

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


...

}

您需要告诉androidManifest.xml您的扩展Application课程。

答案 2 :(得分:1)

  

如何将其传递给其他活动或如何与其共享   其他活动

只需使用 Intent 即可:

intent.putExtra("calc" new Calc(3, 4));

当您想要启动另一个Object时传递此Activity

然后在你的第二个Activity致电:

Calc c = getIntent().getParcelableExtra("calc"); // getSerializableExtra("calc");

您的Calc课程必须实施ParcelableSerializable

public class Calc implements Parcelable { 
 ...
}