首页 > 代码库 > 使用Bundle在Activity间传递数据

使用Bundle在Activity间传递数据

 

使用Bundle在Activity间传递数据

源Activity 

public class SourceActivty extends Activity { 
private Intent intent=null; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
intent=new Intent(); 
Bundle myBundelForName=new Bundle(); 
myBundelForName.putString("Key_Name","1111"); 
myBundelForName.putString("Key_Age","22"); 
intent.putExtras(myBundelForName); 
TextView text=(TextView)findViewById(R.id.test); 
text.setOnClickListener(new OnClickListener() { 
public void onClick(View v) { 
intent.setClass(SourceActivty.this, TargetActivty.class); 
startActivity(intent); 



}); 




目标activty 

public class TargetActivty extends Activity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.intest); 
TextView text=(TextView)findViewById(R.id.tt); 
//从Intent 中获取数据 
Bundle myBundelForGetName=this.getIntent().getExtras(); 
String name=myBundelForGetName.getString("Key_Name"); 
text.setText("欢迎您进入:"+name); 



从源请求Activity 中通过一个Intent 把一个服务请求传到目标Activity 

源activty 

private Intent openWelcomeActivityIntent = null; 
TextView text=null; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 
openWelcomeActivityIntent = new Intent(); 
// 设定开启的下一个Activity 
text=(TextView)findViewById(R.id.test); 
text.setOnClickListener(new OnClickListener() { 
public void onClick(View v) { 
openWelcomeActivityIntent.setClass(SourceActivty1.this, 
TargetActivty1.class); 
startActivityForResult(openWelcomeActivityIntent, 1); 


}); 



@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
super.onActivityResult(requestCode, resultCode, data); 
if (requestCode == 1) { 
if (resultCode == RESULT_CANCELED) { 
setTitle("Cancel****"); 
} else if (resultCode == RESULT_OK) { 
Bundle showBundle = data.getExtras();// 从返回的Intent中获得Bundle 
text.setText("the name get from the second layout:\n" + showBundle.getString("myName")); 







? 第一个参数是你开启请求Intent时的对应请求码,可以自己定义。 
? 第二个参数是目标Activity返回的验证结果码 
? 第三个参数是目标Activity返回的Intent 

目标activty 


public class TargetActivty1 extends Activity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.intest); 
Intent backIntent=new Intent(); 
Bundle stringBundle=new Bundle(); 
stringBundle.putString("myName", "lishiyao"); 
backIntent.putExtras(stringBundle); 
setResult(RESULT_OK, backIntent);//返回Activity结果码 
finish(); 


使用Bundle在Activity间传递数据