Android使用 extras、Bundle、intent无法传值的问题

工作环境(蓝色粗体字为特别注意内容)
1,系统环境:Win7 Ultimate sp1、Android Studio 3.2

很奇怪,今天在使用Bundle在Activity之间传值的时候,居然无法获取传入的值,且看传值代码:

 Bundle bundle = new Bundle();
 bundle.putInt(EXAM_CENTER_TYPE, EXAM_CENTER_1);
 toActivity(ExamTypeActivity.class, bundle);

protected void toActivity(Class<?> clazz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clazz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

取值代码:

    protected Bundle getExtra() {
        Intent intent = getIntent();
        if (intent != null) {
            return getIntent().getExtras();
        } else {
            return null;
        }

    }

    protected String getExtraString(String key) {
        Bundle bundle = getExtra();
        if (bundle != null) {
            return bundle.getString(key);
        } else {
            return "";
        }
    }
    

    protected int getExtraInt(String key) {
      String extra = getExtraString(key);
      return NumberUtils.getInt(extra);
    }

getExtraInt(EXAM_CENTER_TYPE)取不到值,查阅资料之后发现,原因是:传入put 的 数据类型必须和 get 一致 如果你 put 是string get也用string 如果是其他类型 例如 Int 那么 要用getIntExtra();于是getExtraInt函数改为如下函数即可:

  protected int getExtraInt(String key) {
        Bundle bundle = getExtra();
        if (bundle != null) {
            return bundle.getInt(key);
        } else {
            return 0;
        }
    }

猜你喜欢

转载自blog.csdn.net/pang9998/article/details/87992960