android中使用startActivityForResult回传数据(详解)

来源:互联网 发布:java会议管理系统 编辑:程序博客网 时间:2024/06/06 07:26

在使用新浪微博APP时,能发现在微博发布界面进入图库选择图片后,会回到微博发布页面并带回了图片选择页面的图片信息。由于这种需求十分常见,因此,Android提供了一个startActivityForResult()方法,来实现回传数据。

要求:页面1跳转到页面2,页面2再返回页面1同时返回数据

页面1添加如下代码:

 Intent intent = new Intent();   intent.setClass(页面1.this, 页面2.class);   Bundle bundle = new Bundle();   intent.putExtras(bundle);//将Bundle添加到Intent,也可以在Bundle中添加相应数据传递给下个页面,例如:bundle.putString("abc", "bbb");   startActivityForResult(intent, 0);// 跳转并要求返回值,0代表请求值(可以随便写)

 

页面2接收数据添加代码如下:

  

Intent intent = this.getIntent();Bundle bundle = intent.getExtras();bundle.putString("aaa", "back");//添加要返回给页面1的数据intent.putExtras(bundle);this.setResult(Activity.RESULT_OK, intent);//返回页面1this.finish();

 

页面1接收返回数据:(需要重写onActivityResult)

onActivityResult()方法里面的三个参数  第一个参数requestCode,表示再启动Acitivity是传递的请求码  第二个参数resultCode,表示再返回数据时传入结果码 第三个参data,表示携带返回数据的Intent

复制代码
@Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if (requestCode == 0 && resultCode == Activity.RESULT_OK) {            Bundle bundle = data.getExtras();            gameView.backString = bundle.getString("aaa");             Toast.makeText(this, backString, Toast.LENGTH_SHORT).show();        }    }
复制代码


我用一个具体的案例更好的帮助大家理解下startActivityForResult()方法

首先看一下效果图

                                                                   



                       


运行程序,在主界面中分别单机“主人购买装备” “小宝宝购买装备” 按钮  , 会跳转至装备展示界面(第二幅图),装备购买成功后,会看到第三幅图片。

首先创建一个ItemInfo的类  用于封装装备信息。具体代码如下:

public class ItemInfo implements Serializable {    private String name;    private int acctack;    private int life;    private int speed;    public ItemInfo(String name, int acctack, int life, int speed) {        this.name = name;        this.acctack = acctack;        this.life = life;        this.speed = speed;    }    public String getName() {        return name;    }    public int getAcctack() {        return acctack;    }    public int getLife() {        return life;    }    public int getSpeed() {        return speed;    }    public void setName(String name) {        this.name = name;    }    public void setAcctack(int acctack) {        this.acctack = acctack;    }    public void setLife(int life) {        this.life = life;    }    public void setSpeed(int speed) {        this.speed = speed;    }    @Override    public String toString() {        return "ItemInfo{" +                "name='" + name + '\'' +                ", acctack=" + acctack +                ", life=" + life +                ", speed=" + speed +                '}';    }}

需要注意的是Intent除了传递基本数据类型之外,也能传递Serializable或Parcelable类型的数据,为了方便数据传递,在这里让ItemInfo类实现Serializable接口

创建一个ShopActivity是用来展示装备信息的,当单击ShopActivity的装备时,会调用MainActicity并将装备信息回调给MainActivity,ShopActivity的具体代码如下:

public class ShopActivity extends Activity implements View.OnClickListener{    private ItemInfo mItemInfo;    private TextView mLifeTv;    private TextView mNameTv;    private TextView mSpeedTv;    private TextView mAttackTv;    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_shop);        mItemInfo = new ItemInfo("金剑",100,20,20);        findViewById(R.id.rl).setOnClickListener(this);        initWidget();    }    private void initWidget() {        mLifeTv = (TextView) findViewById(R.id.tv_life);        mNameTv = (TextView) findViewById(R.id.tv_name);        mSpeedTv = (TextView) findViewById(R.id.tv_speed);        mAttackTv = (TextView) findViewById(R.id.tv_attack);        mLifeTv.setText("生命值"+ mItemInfo.getLife());        mNameTv.setText(mItemInfo.getName()+"");        mSpeedTv.setText("敏捷度"+ mItemInfo.getSpeed());        mAttackTv.setText("攻击力"+mItemInfo.getAcctack());    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.rl:                Intent intent = new Intent();                intent.putExtra("equipment",mItemInfo);                setResult(1,intent);                finish();                break;        }    }}

MainActivity主要用于响应按钮的点击事件,并将返回的装备信息显示到指定的控件中,具体代码如下:

public class MainActivity extends AppCompatActivity {    private TextView mLifeTv;    private TextView mAttackTv;    private TextView mSpeedTv;    private ProgressBar mProgressBar1;    private ProgressBar mProgressBar2;    private ProgressBar mProgressBar3;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initWidget();    }    private void initWidget() {        mLifeTv = (TextView) findViewById(R.id.tv_life_progress);        mAttackTv = (TextView) findViewById(R.id.tv_attack_progress);        mSpeedTv = (TextView) findViewById(R.id.tv_speed_progress);        mProgressBar1 = (ProgressBar) findViewById(R.id.progressBar1);        mProgressBar2 = (ProgressBar) findViewById(R.id.progressBar2);        mProgressBar3 = (ProgressBar) findViewById(R.id.progressBar3);        mProgressBar1.setMax(100);              // 设置最大值为100        mProgressBar2.setMax(100);        mProgressBar3.setMax(100);    }    public void click(View view){        Intent intent = new Intent(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){            //判断结果码是否等于1 , 等于1为宝宝添加装备            if (resultCode == 1){                if (requestCode == 1){                            ItemInfo info = (ItemInfo) data.getSerializableExtra("equipment");                    // 更新ProgressBar的值                    updatePogress(info);                }            }        }    }    private void updatePogress(ItemInfo info) {        int progress1 = mProgressBar1.getProgress();        int progress2 = mProgressBar2.getProgress();        int progress3 = mProgressBar3.getProgress();        mProgressBar1.setProgress(progress1+info.getLife());        mProgressBar2.setProgress(progress2+info.getAcctack());        mProgressBar3.setProgress(progress3+info.getSpeed());        mLifeTv.setText(mProgressBar1.getProgress()+"");        mAttackTv.setText(mProgressBar2.getProgress()+"");        mSpeedTv.setText(mProgressBar3.getProgress()+"");    }}

xml的代码如下:

activity_main.xml如下:

<LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:gravity="center"    android:orientation="vertical"    >    <ImageView        android:id="@+id/pet_imgv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"        android:layout_marginBottom="5dp"        android:layout_marginTop="30dp"        android:src="@mipmap/ic_launcher"/>    <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_horizontal"        android:text="主人,快给小宝宝买装备吧"/>    <TableLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_marginBottom="25dp">        <TableRow            android:layout_width="match_parent"            android:layout_height="wrap_content"            >            <TextView                android:layout_width="0dp"                android:layout_height="wrap_content"                android:layout_weight="1"                android:text="生命值"                android:textColor="@android:color/black"                android:textSize="14sp"/>            <ProgressBar                android:id="@+id/progressBar1"                style="?android:attr/progressBarStyleHorizontal"                android:layout_width="0dp"                android:layout_height="wrap_content"                android:layout_gravity="center"                android:layout_weight="2"/>            <TextView                android:id="@+id/tv_life_progress"                android:layout_width="0dp"                android:layout_height="wrap_content"                android:layout_weight="1"                android:gravity="center"                android:text="0"                android:textColor="#000000"/>        </TableRow>    </TableLayout>    <TableLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_marginBottom="25dp">        <TableRow            android:layout_width="match_parent"            android:layout_height="wrap_content"            >            <TextView                android:layout_width="0dp"                android:layout_height="wrap_content"                android:layout_weight="1"                android:text="攻击力"                android:textColor="@android:color/black"                android:textSize="14sp"/>            <ProgressBar                android:id="@+id/progressBar2"                style="?android:attr/progressBarStyleHorizontal"                android:layout_width="0dp"                android:layout_height="wrap_content"                android:layout_gravity="center"                android:layout_weight="2"/>            <TextView                android:id="@+id/tv_attack_progress"                android:layout_width="0dp"                android:layout_height="wrap_content"                android:layout_weight="1"                android:gravity="center"                android:text="0"                android:textColor="#000000"/>        </TableRow>    </TableLayout>    <TableLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_marginBottom="25dp">        <TableRow            android:layout_width="match_parent"            android:layout_height="wrap_content"            >            <TextView                android:layout_width="0dp"                android:layout_height="wrap_content"                android:layout_weight="1"                android:text="敏捷"                android:textColor="@android:color/black"                android:textSize="14sp"/>            <ProgressBar                android:id="@+id/progressBar3"                style="?android:attr/progressBarStyleHorizontal"                android:layout_width="0dp"                android:layout_height="wrap_content"                android:layout_gravity="center"                android:layout_weight="2"/>            <TextView                android:id="@+id/tv_speed_progress"                android:layout_width="0dp"                android:layout_height="wrap_content"                android:layout_weight="1"                android:gravity="center"                android:text="0"                android:textColor="#000000"/>        </TableRow>    </TableLayout>    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_marginLeft="50dp"        android:layout_marginRight="50dp"        android:layout_marginTop="20dp">        <Button            android:id="@+id/btn_baby"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:onClick="click"            android:text="小宝宝购买装备"            android:textSize="14sp"/>    </RelativeLayout></LinearLayout>
装备界面的xml如下:activity_shop.xml 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"                android:id="@+id/rl"                android:layout_width="match_parent"                android:layout_height="match_parent"                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/tv_name"        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/tv_life"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="生命值"            android:textSize="13sp"/>        <TextView            android:id="@+id/tv_attack"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="攻击力"            android:textSize="13sp"/>        <TextView            android:id="@+id/tv_speed"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="速度"            android:textSize="13sp"/>    </LinearLayout></RelativeLayout>





原创粉丝点击