Activity的传值和回传值(4)

@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

我们看到,这里我们使用的是 startActivityForResult 的这个方法,

public void startActivityForResult (Intent intent, int requestCode)

Same as calling startActivityForResult(Intent, int, Bundle) with no options.

Parameters
intent    The intent to start.
requestCode    If >= 0, this code will be returned in onActivityResult() when the activity exits.

Throws   android.content.ActivityNotFoundException

第一个指定我们的Intent对象,第二个requestCode指定我们的一个启动标志值,因为我们可能有多个按钮,如果都是跳转到同一个Activity对象上,我们需要对其进行标志,才知道是哪个Activity对象跳转过来的。

我们看到这里还有一个 onActivityResult 方法,这个方法就是用来处理我们Activity的回传值的方法,所有的Activity回传值的操作都是在这个方法中完成。

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

Called when an activity you launched exits, giving you the requestCode you started it with, the resultCode it returned, and any additional data from it. The resultCode will be RESULT_CANCELED if the activity explicitly returned that, didn't return any result, or crashed during its operation.

You will receive this call immediately before onResume() when your activity is re-starting.

Parameters
requestCode    The integer request code originally supplied to startActivityForResult(), allowing you to identify who this result came from.
resultCode    The integer result code returned by the child activity through its setResult().
data    An Intent, which can return result data to the caller (various data can be attached to Intent "extras").

接下来,我们看看SecondActivity这个类:

public class SecondActivity extends Activity
{
    private Button button;
    private TextView textView;
    private EditText editText;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
       
        button = (Button)findViewById(R.id.button1);
        textView = (TextView)findViewById(R.id.textView1);
        editText = (EditText)findViewById(R.id.editText1);
       
        Intent intent = getIntent();
        String message = intent.getStringExtra("message").toString().trim();
        textView.setText(message);
       
        button.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                String result = editText.getText().toString().trim();
                Intent intent = new Intent();
                intent.putExtra("result", result);
                /*
                * 调用setResult方法表示我将Intent对象返回给之前的那个Activity,这样就可以在onActivityResult方法中得到Intent对象,
                */
                setResult(1001, intent);
                //    结束当前这个Activity对象的生命
                finish();
            }
        });
    }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/0a520616481597c0f735d373c6409a7a.html