Android跳转新页面,并在新页面关闭后传值给本页面,onActivityResult 方法实现

一、使用场景,假设有一个activity 名称为 WarehousingOutActivity ,希望在WarehousingOutActivity跳转到新页面 LocationGoodsSelectActivity,并传值过去,在LocationGoodsSelectActivity页面销毁的时候,再将处理后的数据传回WarehousingOutActivity

实现:

在WarehousingOutActivity中,跳转到LocationGoodsSelectActivity,并携带对象参数 (对象名为:toLocationGoodsSelect  该对象需要实现 Serializable接口):

Intent intent = new Intent(WarehousingOutActivity.this, LocationGoodsSelectActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("toLocationGoodsSelect", toLocationGoodsSelect);
        intent.putExtras(bundle);
        WarehousingOutActivity.this.startActivityForResult(intent, ActivityRequestCode.TO_LOCATION_GOODS_SELECT);

重写 onActivityResult 方法:

@Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ActivityRequestCode.TO_LOCATION_GOODS_SELECT:
                    Map<Long, List<GoodsBatchTakeParam>> resultMap = (Map<Long, List<GoodsBatchTakeParam>>) data.getSerializableExtra("resultMap");
                    Toast.makeText(WarehousingOutActivity.this, QMUITipDialog.Builder.ICON_TYPE_FAIL, resultMap.toString());
                    break;
            }
        }
    }

在LocationGoodsSelectActivity中,接收上一个页面传进来的数据,onCreate方法中:

Intent intent = getIntent();
        toLocationGoodsSelect = (ToLocationGoodsSelect) intent.getSerializableExtra("toLocationGoodsSelect");

就拿到了刚刚传过来的对象:toLocationGoodsSelect 

想要在LocationGoodsSelectActivity 再传回数据到WarehousingOutActivity中,就在页面销毁之前:

Intent intent = new Intent(LocationGoodsSelectActivity.this, WarehousingOutActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("resultMap", (Serializable) resultMap);
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        finish();

为了方便附:

ActivityRequestCode.java 代码:

public class ActivityRequestCode {

    /**
     * 出库 去商品库位选择页
     */
    public static final int TO_LOCATION_GOODS_SELECT = 10001;
}

就这样可以了,直接复制代码肯定报错,因为有些我自己自定义的变量,你可以替换成自己的,思路是这样的,一般你既然要用到,那你肯定会基础的android,你就很简单的改造一下即可。

上一篇:Android Intent的几种跳转方式


下一篇:【9月学习随笔】关于Webpack