Android 2个activity 之间的数据传递

1.通过intent来传递:

A.传字符等:activity1中设置:

Java代码

String text = "hello";

Intent intent1 = new Intent(ActivityMain.this, Activity2.class);

intent1.putExtra("activity1", text);

startActivity(intent1 );

String text = "hello";

Intent intent1 = new Intent(ActivityMain.this, Activity2.class);

intent1.putExtra("activity1", text);

startActivity(intent1 );

B.传对象,对象要实例化,继承Serializable

Java代码

Bundle mbundle=new Bundle(); mbundle.putSerializable("user",userList.get(position));

Intent in =new Intent (getApplicationContext(), activity2.class);

in.putExtras(mbundle);

startActivity(in);

Bundle mbundle=new Bundle(); mbundle.putSerializable("user",userList.get(position));

Intent in =new Intent (getApplicationContext(), activity2.class);

in.putExtras(mbundle);

startActivity(in);

activity2中接收:

A:接收

Java代码

Bundle extras = getIntent().getExtras();

if (extras != null) {

textview.setText(extras.getString("activity1"));

}

Bundle extras = getIntent().getExtras();

if (extras != null) {

textview.setText(extras.getString("activity1"));

}

B.接收

Java代码

Bundle bundel = getIntent().getExtras();

user= (User) bundel.get("user");

Bundle bundel = getIntent().getExtras();

user= (User) bundel.get("user");

2.SharedPreferences

我在activity1中设置的如下:

Java代码

SharedPreferences sp =getSharedPreferences("textinfo",0);

Editor editor=sp.edit();

String text = "hello";

editor.putString("text", text);

editor.commit();Intent i = new Intent(getApplicationContext(),activity2.class);

startActivity(i);

SharedPreferences sp =getSharedPreferences("textinfo",0);

Editor editor=sp.edit();

String text = "hello";

editor.putString("text", text);

editor.commit();

Intent i = new Intent(getApplicationContext(),activity2.class);

startActivity(i);

跳转到Message的activity,获取内容如下

Java代码

SharedPreferences share=getSharedPreferences("textinfo",0);

String text =share.getString("text", null);

msgtextview.setText(text);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值