Activity参数传递
1.如果数据较少,比如只要传一个字符串,可以使用如下代码:
在Activity A中:
Intent intent = new Intent(A.this, B.class);
intent.putExtra("Name", "name");
startActivity(intent);
在Activity B中:
Intent intent = this.getIntent();
String name = intent.getStringExtra("Name");
2.如果数据比较多,就需要使用 Bundle类,代码如下:
在Activity A中传值:
Intent intent = new Intent(A.this, B.class);
//通过Bundle对象存储需要传递的数据
Bundle bundle = new Bundle();
//字符、字符串、布尔、字节数组、浮点数等等,都可以传
bundle.putString("Name", "name");
bundle.putBoolean("Isgood", true);
//把bundle对象assign给Intent
intent.putExtras(bundle) //另一种方式intent.putExtra("data",bundle);
startActivity(intent);
在Activity B中获取传递的值:
//获取Intent中的Bundle对象
Bundle bundle = this.getIntent().getExtras(); //Bundle bundle = this.getIntent().getBundleExtra(“data”);
//获取Bundle中的数据,注意类型和key
String name = bundle.getString(“Name”);
boolean ismale = bundle.getBoolean(“Isgood”);
3.还可以传递对象,通过让一个类实现Serializable或者Parcelable接口实现对该类对象的传递。
Serializable是java提供的序列化接口,没有要实现的接口函数。
在A中传递User的对象user
intent.putExtra(“user”,new User(“jikexueyuan”,2));
在B中接受数据:创建一个user对象
User user = (User) intent.getSerializableExtra(“user”);
而Parcelable是Android提供的更快但是复杂的序列化接口。需要在User(String name ,int age)类中实现接口函数:
public int describeContents(){
return = 0;
}
public void writeToParcel(Parcel dest , int flags){
dest.writeString(getname());
dest.writeInt(getage());
}
还需要实现函数:
public static final Creator CREATOR = new Creator() {
public User createFromParcel (Palcel source){
return new User(source.readString(),source.readInt()
}
public User[] newArray(int size)
{
return new User[size];
}
};
B接受时:
User user = intent.getParcelableExtra(“user”);
4.获取Acitivity返回参数
B中传回参数:
Intent i = new Intent();
i.putExtra(“data”,”sd”);
setResult(resultCode,i);
finish();//结束当前程序
A中接受返回的参数:
使用
startActivityForResult(intent,requestCode);//启动A
并且重载一个函数获取数据
protected void onActivityResult(int requesstCode ,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
String st= data.getStringExtra("data");//获取返回参数
}