一、简介
前面己经提到,Activity 还提供了一个 startActivityForResult(Intent intent, int requestCode) 方法来启动其他Activity。该方法用于启动指定Activity,而且期望获取指定Activity返回的结果。这种请求对于实际应用也是很常见的,例如应用程序第一个界面需要用户进行选择——但需要选择的列表数据比较复杂,必须启动另一个Activity让用户选择。当用户在第二个Activity 中选择完成后,程序返回第一个Activity,第一个Activity必须能获取并显示用户在第二个 Activity中选择的结果。在这种应用场景下,也是通过Bundle进行数据交换的。
为了获取被启动的Activity所返回的结果,需要从以下三方面着手。
使用startActivityForResult(Intent intent, int requestCode) 方法启动指定Activity。
当前 Activity 需要重写 onActivityResult(int requestCode,int resultCode,Intent intent), 当被启动的Activity返回结果时,该方法将会被触发,其中requestCode代表请求码, 而resultCode代表Activity返回的结果码,这个结果码也是由开发者根据业务自行设定的。
被启动的Activity需要调用setResult()方法设置处理结果。
关于启动Activity并回传数据的核心代码如下所示:
// 启动SecondActivity
Intent intent=new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(intent,1);
// 从SecondActivity返回数据给MainActivity
Intent intent=new Intent();
intent.putExtra("extra_data_name","admin");
setResult(1,intent);
SecondActivity.this.finish();
上述本例代码中,startActivityForResult()方法接收两个参数,第一个参数是Intent,第二个参数是请求码,用于在判断数据的来源。setResult()方法也接收两个参数,第一个参数resultCode结果码,第二个参数则是把带有数据的Intent传递回去。
然后是在启动SecondActivity的MainActivity中重写onActivityResult()方法,实现获取返回的数据,核心代码如下:
// 处理SecondActivity返回来的数据
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if(1==resultCode){
String name=data.getStringExtra("extra_data_name");
}
}
上述代码中,onActivityResult()方法有三个参数,第一个参数requestCode表示在启动Activity时传递的请求码;第二个参数resultCode表示在返回数据时传入结果码;第三个参数data表示携带返回数据的Intent。
需要注意的是,在一个Activity中很可能调用startActivityForResult()方法启动多个 Activity,每一个Activity返回的数据都会回调到onActivityResult()这个方法中,因此,首先要做的就是通过检查requestCode的值来判断数据来源,确定数据是从SecondActivity返回的,然后再通过resultCode的值来判断数据处理结果是否成功,最后从data中取出数据,这样就完成了 Activity中数据返回的功能。
二、示例
接下来通过一个示例来学习Activity如何通过Bundle回传数据。
创建一个示例程序,也非常简单,模拟游戏里面的装备升级,主要包括两个界面,其中第一个界面为角色当前装备的实力,可以通过按钮跳转到商店页面购买所需的装备,然后返回升级原来的装备等级。
程序对应的主布局文件(activity_main.xml )如下所示:
[代码]xml代码:
<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical" android:gravity = "center" > < ImageView android:id = "@+id/pet_img" android:layout_width = "120dp" android:layout_height = "120dp" android:layout_gravity = "center_horizontal" android:layout_marginBottom = "5dp" android:src = "@drawable/pet" /> < TextView android:id = "@+id/pet_dialog_tv" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_gravity = "center_horizontal" android:layout_marginBottom = "25dp" android:gravity = "center" android:text = "主人,快给小宝宝购买装备吧" /> < TableLayout android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:layout_gravity = "center" android:layout_marginBottom = "20dp" android:padding = "20dp" > < TableRow android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:padding = "10dp" > < TextView android:layout_width = "0dip" android:layout_height = "wrap_content" android:layout_weight = "1" android:text = "生命值:" android:textColor = "@android:color/black" android:textSize = "14sp" /> < ProgressBar android:id = "@+id/life_pb" style = "?android:attr/progressBarStyleHorizontal" android:layout_width = "0dip" android:layout_height = "wrap_content" android:layout_gravity = "center" android:layout_weight = "3" /> < TextView android:id = "@+id/life_progress_tv" android:layout_width = "0dip" android:layout_height = "wrap_content" android:layout_weight = "1" android:text = "0" android:gravity = "center" android:textColor = "#000000" /> </ TableRow > < TableRow android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:padding = "10dp" > < TextView android:layout_width = "0dip" android:layout_height = "wrap_content" android:layout_weight = "1" android:text = "攻击力:" android:textColor = "@android:color/black" android:textSize = "14sp" /> < ProgressBar android:id = "@+id/attack_pb" style = "?android:attr/progressBarStyleHorizontal" android:layout_width = "0dip" android:layout_height = "wrap_content" android:layout_weight = "3" /> < TextView android:id = "@+id/attack_progress_tv" android:layout_width = "0dip" android:layout_height = "wrap_content" android:layout_weight = "1" android:text = "0" android:gravity = "center" android:textColor = "#000000" /> </ TableRow > < TableRow android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:padding = "10dp" > < TextView android:layout_width = "0dip" android:layout_height = "wrap_content" android:layout_weight = "1" android:text = "敏捷:" android:textColor = "@android:color/black" android:textSize = "14sp" /> < ProgressBar android:id = "@+id/speed_pb" style = "?android:attr/progressBarStyleHorizontal" android:layout_width = "0dip" android:layout_height = "wrap_content" android:layout_weight = "3" /> < TextView android:id = "@+id/speed_progress_tv" android:layout_width = "0dip" android:layout_height = "wrap_content" android:layout_weight = "1" android:text = "0" android:gravity = "center" android:textColor = "#000000" /> </ TableRow > </ TableLayout > < RelativeLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:gravity = "center_horizontal" > < Button android:id = "@+id/buy_btn" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_alignParentLeft = "true" android:layout_alignParentTop = "true" android:drawableRight = "@android:drawable/ic_menu_add" android:drawablePadding = "3dp" android:text = "主人购买装备" android:textSize = "14sp" /> </ RelativeLayout > </ LinearLayout > |
上述布局代码使用到了控件ProgressBar (进度条),它是用来显示小宝宝的生命值,攻击力和敏捷度的。
创建装备选择界面activity_shop.xml,该界面是来选择装备的,代码如下所示。
[代码]xml代码:
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:id = "@+id/buy_rl" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:orientation = "vertical" > < View android:layout_width = "30dp" android:layout_height = "30dp" android:layout_alignParentLeft = "true" android:layout_centerVertical = "true" android:background = "@android:drawable/ic_menu_info_details" /> < TextView android:id = "@+id/name_tv" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_centerVertical = "true" android:layout_marginLeft = "60dp" android:text = "商品名称" /> < LinearLayout android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_centerInParent = "true" android:orientation = "vertical" > < TextView android:id = "@+id/life_tv" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "生命值" android:textSize = "13sp" /> < TextView android:id = "@+id/attack_tv" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "攻击力" android:textSize = "13sp" /> < TextView android:id = "@+id/speed_tv" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "速度" android:textSize = "13sp" /> </ LinearLayout > </ RelativeLayout > |
ShopActivity是用来展示装备信息的,当单击ShopActivity的装备时,会调回MainActivity并将装备信息回传给MainActivity。ShopActivity的具体代码如下所示:
[代码]java代码:
package com.jinyu.cqkxzsxy.android.activity.equipmentupdate; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; public class ShopActivity extends AppCompatActivity implements View.OnClickListener { public static final String DATA_KEY_NAME = "name" ; public static final String DATA_KEY_LIFE = "life" ; public static final String DATA_KEY_SPEED = "speed" ; public static final String DATA_KEY_ATTACK = "attack" ; private static final String NAME = "小宝" ; private static final int LIFE_VALUE = 20 ; private static final int SPEED_VALUE = 30 ; private static final int ATTACK_VALUE = 10 ; protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_shop); TextView mLifeTV = (TextView) findViewById(R.id.life_tv); TextView mNameTV = (TextView) findViewById(R.id.name_tv); TextView mSpeedTV = (TextView) findViewById(R.id.speed_tv); TextView mAttackTV = (TextView) findViewById(R.id.attack_tv); mNameTV.setText(NAME); mLifeTV.setText( "生命值+" + LIFE_VALUE); mSpeedTV.setText( "敏捷度+" + SPEED_VALUE); mAttackTV.setText( "攻击力+" + ATTACK_VALUE); findViewById(R.id.buy_rl).setOnClickListener( this ); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.buy_rl: Intent intent = new Intent(); Bundle data = new Bundle(); data.putString(DATA_KEY_NAME, NAME); data.putInt(DATA_KEY_LIFE, LIFE_VALUE); data.putInt(DATA_KEY_SPEED, SPEED_VALUE); data.putInt(DATA_KEY_ATTACK, ATTACK_VALUE); intent.putExtras(data); setResult( 1 , intent); finish(); break ; } } } |
从上述代码中可以看出,setReult()方法的作用是让当前Activity返回到它的调用者,在这里可以理解为让ShopActivity返回到MainActivity。
接下来编写MainActivity。MainActivity主要用于响应按钮的点击事件,并将返回的装备信息显示到指定的控件中,具体代码如下所示:
[代码]java代码:
package com.jinyu.cqkxzsxy.android.activity.equipmentupdate; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private Button mBuyBtn = null ; private ProgressBar mLifePb = null ; private ProgressBar mAttackPb = null ; private ProgressBar mSpeedPb = null ; private TextView mLifeTV = null ; private TextView mAttackTV = null ; private TextView mSpeedTV = null ; protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBuyBtn = (Button) findViewById(R.id.buy_btn); mLifeTV = (TextView) findViewById(R.id.life_progress_tv); mAttackTV = (TextView) findViewById(R.id.attack_progress_tv); mSpeedTV = (TextView) findViewById(R.id.speed_progress_tv); mLifePb = (ProgressBar) findViewById(R.id.life_pb); mAttackPb = (ProgressBar) findViewById(R.id.attack_pb); mSpeedPb = (ProgressBar) findViewById(R.id.speed_pb); mLifePb.setMax( 100 ); mAttackPb.setMax( 100 ); mSpeedPb.setMax( 100 ); mBuyBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity. this , ShopActivity. class ); startActivityForResult(intent, 1 ); // 返回请求结果,请求码为1 } }); } @Override protected void onActivityResult( int requestCode, int resultCode, Intent data) { super .onActivityResult(requestCode, resultCode, data); if (data != null ) { if (resultCode == 1 ) { if (requestCode == 1 ) { Bundle equipment = data.getExtras(); //更新ProgressBar的值 updateProgress(equipment); } } } } //更新ProgressBar的值 private void updateProgress(Bundle info) { int lifeProgress = mLifePb.getProgress(); int attackProgress = mAttackPb.getProgress(); int speedProgress = mSpeedPb.getProgress(); mLifePb.setProgress(lifeProgress + info.getInt(ShopActivity.DATA_KEY_LIFE)); mAttackPb.setProgress(attackProgress + info.getInt(ShopActivity.DATA_KEY_ATTACK)); mSpeedPb.setProgress(speedProgress + info.getInt(ShopActivity.DATA_KEY_SPEED)); mLifeTV.setText(mLifePb.getProgress() + "" ); mAttackTV.setText(mAttackPb.getProgress() + "" ); mSpeedTV.setText(mSpeedPb.getProgress() + "" ); } } |
使用Activity时需要在清单文件中配置,具体代码如下所示:
[代码]xml代码:
<? xml version = "1.0" encoding = "utf-8" ?> < manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.jinyu.cqkxzsxy.android.activity.equipmentupdate" > < application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme" > < activity android:name = ".MainActivity" android:label = "我的装备" > < intent-filter > < action android:name = "android.intent.action.MAIN" /> < category android:name = "android.intent.category.LAUNCHER" /> </ intent-filter > </ activity > < activity android:name = ".ShopActivity" android:label = "购买装备" /> </ application > </ manifest > |
运行程序,在主界面中单击“主人购买装备”按钮,会跳转至装备购买页面,如中图所示。
装备购买成功后,会返回主页面。从右图可以看出,主人购买装备完成后,购买的装备会显示在界面控件中,并且进度条的值会随着装备的购买而增加。
本节和上一节分别学习了简单数据在Activity之间的传递,下期一起来学习复杂数据的传递。
今天就先到这里,如果有问题欢迎留言一起探讨,也欢迎加入Android零基础入门技术讨论微信群,共同成长!