Android通过startActivityForResult来传递数据

木来 木来

(1)需要有两个Activity,一个FirstActivity和SecondActivity

(2)在FirstActivity的布局中写一个button控件,然后在活动中实现button的点击函数,然后在函数体内写

Intent intent=new Intent(FirstActivity.this,SecondActivity.class);
startActivityForResult(intent,1);

(3)在被跳转后的secondActivity创建一个button控件,然后在button的点击事件中写

Intent intent=new Intent();
intent.putExtra("msg","hello!first!!!!!");
setResult(RESULT_OK,intent);
finish();

(4)在firstActivity活动中重写回调后的onActivityResult来接收数据

private static final String TAG = "FirstActivity";
@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

    switch (requestCode){
        case 1:
            if(resultCode==RESULT_OK){
                String msg=data.getStringExtra("msg");
                Log.w(TAG,msg);
            }
            break;
    }




}
0 条评论