欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Activity之间交换数据

程序员文章站 2022-03-30 08:57:16
...

1. Bundle

  • Bundle是一个字符串值到各种Parcelable类型的映射,用于保存要携带的数据包。

ActivityFirst

//保存
Intent intent = new Intent(ActivityFirst.this, ActivitySecond.class);
Bundle bundle = new Bundle();
bundle.putCharSequende("key", value);
intent.putExtras(bundle);
startActivity(intent);

ActivitySecond

//提取
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String str = bundle.getString("key");

2. startAcitivityForResult()

ActivityFirst

final int Code = 0x1;//请求码
Intent intent = new Intent(ActivityFirst.this, ActivitySecond.class);
startAcitivityForResult(intent, Code);//带请求码启动

//重写,setResult()的回调
protected void OnActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == Code && resultCode == Result)
     ...
}

ActivitySecond

final int Result = 0x2;//结果码
Intent intent = new Intent(ActivitySecond.this, ActivityFirst.class);
setResult(Result, intent);
finish();//返回First并结束当前