Activity参数传递

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");//获取返回参数
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值