startActivityForResult的用法

业务场景:
洋哥描述:Activity在finish的时候需要向上一个Activity传值
官方描述:主Activity需要在子Activityfinish的时候(出栈)获取到子Acitivity的数据(本质还是用的intent的bundle进行的传参)

public class MainActivity extends AppCompatActivity {
    private TextView textview;
    private static final int REQUEST_CODE=1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(MainActivity.this,
                        SecondActivity.class), REQUEST_CODE);
            }
        });
        textview = (TextView) findViewById(R.id.textview);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            String s = data.getStringExtra("bian");
            textview.setText(s);
        }
    }
}

子Activity

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        final EditText text1 = (EditText) findViewById(R.id.text1);
        Button finish = (Button) findViewById(R.id.finish);
        finish.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
//                Intent mIntent = new Intent();

                Intent mIntent = getIntent();
                mIntent.putExtra("bian", text1.getText().toString());
                setResult(RESULT_OK, mIntent);
                finish();
            }
        });
    }
}

你可能感兴趣的:(Android)