我新建了一个对象int avtivity1.I想将它传输给activity2.And只传输引用,而不是复制它。我需要怎么做?
public class MyActivity1 extends Activity{
public void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.main);
myButton1 = (Button)findViewById(R.id.ButtonId1);
myButton1.setText("goto");
myButton1.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
MyObject myObject = new MyObject();
//how to transmit the object reference to OtherActiviy
//I want only transmit,not copy the object
Intent intent = new Intent();
intent.setClass(MyActivity1.this, OtherActiviy.class);
startActivity(intent);
}
});
}
}
答案 0 :(得分:0)
您可以将扩展Parcelable或Serialization的Object放入intent中。 或者一个糟糕的方法是在Activity1上将对象解析为String by Gson,并将String转换为Activity2上的对象。
答案 1 :(得分:-1)
你可以这样做:
public class MyActivity1 extends Activity{
public void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.main);
myButton1 = (Button)findViewById(R.id.ButtonId1);
myButton1.setText("goto");
myButton1.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
MyObject myObject = new MyObject();
//how to transmit the object reference to OtherActiviy
//I want only transmit,not copy the object
Intent intent = new Intent();
intent.putExtra("MYObject",myObject);
intent.setClass(MyActivity1.this, OtherActiviy.class);
startActivity(intent);
}
});
}
注意:myObject应该是可以分配的。