Activity之间的三种传值方式

***************************************

第一种:Extras:额外的,附加的.在Intent中附加额外的消息

//传值

Intent intent = new Intent(this, XXXActivity.class);

intent.putExtra(key, value);

startActivity(intent);

//取值

getIntent()方法得到intent对象

Intent intent = getIntent();

//获取Intent中的数据:getXXXExtra()方法

intent.getIntExtra(key, value);--->int

intent.getStringExtra(key);--->String

显示方式:

吐司:Toast.makeText(this, "", Toast.LENGTH_SHORT).show();

打印:Log.i("TAG", "....");

显示在TextView控件上:

mTextView.setText();

******************************************************

第二种:Bundle传值

//传值:

Intent对象

Intent intent = new Intent(.......);

创建Bundle对象,包裹数据

Bundle bundle = new Bundle();

bundle.putInt(key, value);

bundle.putString(...);

bundle.putBoolean(...);

......

将bundle挂载到Intent对象上

intent.putExtras(bundle);

跳转页面

startActivity(intent);

//取值

getIntent()得到intent对象

获取Bundle对象

intent.getExtras();--->Bundle bundle

bundle.getInt(key);

bundle.getString(key);

...........

显示:同上

*************************************************

第三种:通过对象方式传值

//传值

Intent intent = new Intent(this, XXXActivity.class);

创建一个类实现序列化(Person为例)

部分代码:

public class Person implements Serializable{

 private static final long serialVersionUID = 1L;

 private String name;

 private List<String> list;

 ....}

创建Person对象

Person person = new Person();

person.setName(...);

List<String> list = new ArrayList<>();

list.add(...);

person.setList(list);

在intent上设置序列化对象

intent.putExtra(key, person);

跳转

startActivity(intent);

//取值

获取intent对象

getIntent();-->Intent intent

获取序列化对象

intent.getSerializableExtra(key);-->Person person

显示在TextView上:

mTextView.setText(person.toString());

猜你喜欢

转载自blog.csdn.net/yiyihuazi/article/details/82941312