以下图,用户在第一个页面填写完数据后点击“计算”按钮,程序跳转到第二个页面,并显示计算结果。在用户点击第二个页面的“返回计算结果”按钮后,程序跳转回第一个页面,并显示第二个页面的计算结果,注意第一个页面的变化。html
一、在第一个页面(MainActivity.java)中以方法startActivityForResult( )启动第二个页面(TwoActivity.java);java
01.
private
void
jump2Activiy2() {
this
02.
spa
03.
Bundle bundle =
new
Bundle();
.net
04.
bundle.putString(
"strSex"
, strSex);
code
05.
bundle.putDouble(
"douHeight"
, douHeight);
orm
06.
Intent intent =
new
Intent();
htm
07.
intent.setClass(MainActivity.
this
, TwoActivity.
class
);
get
08.
intent.putExtra(
"bundle"
, bundle);
09.
startActivityForResult(intent,
0
);
10.
}
二、在第二个页面中对要返回的数据进行打包,并以方法setResult( )返回第一个页面;
01.
private
void
jump2Activiy1() {
02.
03.
Intent intent2 =
new
Intent();
04.
intent2.setClass(TwoActivity.
this
, MainActivity.
class
);
05.
Bundle bundle2 =
new
Bundle();
06.
bundle2.putString(
"strResult"
, strResult);
07.
intent2.putExtra(
"bundle2"
, bundle2);
08.
setResult(
0
, intent2);
09.
TwoActivity.
this
.finish();
10.
}
三、在第一个页面中复写onActivityResult( )方法,用于获取和处理第二页面返回的数据,更新页面。
01.
@Override
02.
protected
void
onActivityResult(
int
requestCode,
int
resultCode, Intent data) {
03.
if
(
0
== requestCode) {
04.
if
(
0
== resultCode) {
05.
06.
Bundle bundle2 = data.getBundleExtra(
"bundle2"
);
07.
String strFromAct2 = bundle2.getString(
"strResult"
);
08.
txtFromAct2.setText(strFromAct2);
09.
}
10.
11.
}
12.
super
.onActivityResult(requestCode, resultCode, data);
13.
}
利用Intent和Bundle实现不一样Activity之间数据的传递,此种方法虽然简单易懂,可是总感受与MVC思想有所背离,最好是能将页面和数据分开,经过更改数据来调整页面,而不是让数据在两个Activity之间“抛过来,抛过去”,或许Fragment的诞生有此种考虑也未可知。
以上谨表明我的意见,抛砖引玉,代码有写做不规范的地方,接受走过的路过的直接拍砖斧正。
源码下载http://download.csdn.net/detail/liyongliang_2012/7556133 文件名:HelloAndroid20140627.rar