我可以在第一个活动中初始化对象吗?你可以在所有活动中初始化对象???
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。
如何将其传递给其他活动或如何与其他活动共享
答案 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
课程必须实施Parcelable
或Serializable
public class Calc implements Parcelable {
...
}