您的位置:首页 > 其它

Activity 之间传递参数和返回参数的方法

2016-08-17 17:32 351 查看
需要声明的包

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

1,传递参数的方法,在源Activity中实现如下:

{

       Intent intent = new Intent();

        Bundle bd = new Bundle();

        bd.putInt("a", 0xa);

        bd.putInt("b", 0xb);

        bd.putInt("c", 0xC);

        bd.putInt("d", 0xd);

        bd.putInt("e", 0xe);

        intent.putExtra("bundle", bd);

        intent.putExtra(“test1”, "1");

        intent.putExtra("test2", "2");

       //startActivity(intent); /**不需要返回方式***/

        startActivityForResult(intent,REQUEST_SEARCH_CODE);

}

2,获取参数的方法,在目的Activity中实现如下:

{

  Intent intent = getIntent();

 String test1 = intent.getStringExtra(“test1”);

 String test2 = intent.getStringExtra(“test2”);

 Bundle bd = intent.getBundleExtra("bundle");

 int a = bd.getInt("a");

int b = bd.getInt("b");

int c = bd.getInt("c");

}

3,返回的方法;在上一个Activity中实现如下:

{

        Intent intent = new Intent();

        Bundle bd = new Bundle();

        bd.putInt("a", 0xa);

        bd.putInt("b", 0xb);

        bd.putInt("c", 0xC);

        bd.putInt("d", 0xd);

        bd.putInt("e", 0xe);

        intent.putExtra("bundle", bd);

        intent.putExtra(“test1”, "1");

        intent.putExtra("test2", "2");
        setResult(resultCode,intent);

        this.finish();

}

4,获取返回参数的方法(只限于startActivityForResult对应使用):在当前Activity中实现如下:

{

    @Override  

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {  

    super.onActivityResult(requestCode, resultCode, data);

    Log.i(TAG, "onActivityResult request:"+requestCode+", resultCode:" + resultCode + "\n");

    switch(resultCode)  

    {  

       case A:

          

                 String test1 = data.getStringExtra(“test1”);

                 String test2 = data.getStringExtra(“test2”);

                  Bundle bd = data.getBundleExtra("bundle");

                  int a = bd.getInt("a");

                  int b = bd.getInt("b");

                  int c = bd.getInt("c");

           break;

       default:

           break;

    }

   }
}

其中,requestCode为startActivityForResult(intent,REQUEST_SEARCH_CODE);的REQUEST_SEARCH_CODE的值;resultCode为上个ActivitysetResult(resultCode,intent)的resultCode,data为ActivitysetResult(resultCode,intent)的intent;

经常遇到的问题是,当前activity 没有堵塞,而是开了新的栈给新的Activity,导致马上返回的值不正确,原因是在AndroidManifest,xml android:launchMode设置的mode 为singleInstance,而是采用"standard";或是这种方式就不能用这种方式回传参数!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  activity