1. Using the project created in the previous article, add text boxes and buttons to the Secondactivity.xml file, with the following code:
<textview android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "Please enter your name"/> <edittext android:id= "@+id/txt_username" android:layout_width= "Fill_ Parent " android:layout_height=" wrap_content "/> <button android:id=" @+id/btn_ok " Android : layout_width= "fill_parent" android:layout_height= "wrap_content" android:onclick= "OnClick " android:text= "OK"/>
2, add the onclick () method in the Secondactivity.java file, the code is as follows:
public void OnClick (View v) {Intent data = new Intent (); EditText txt_username = (EditText) Findviewbyid (r.id.txt_username);//Use the SetData () method to return data using a intent object Data.setdata ( Uri.parse (Txt_username.gettext (). toString ()));//Setresult () method sets the result code and the data to be passed back to the calling activity Setresult (RESULT_OK, data);// Close Activityfinish ();}
3. Add the following code to the Mainactivity.java file:
In the OnClick () method:
Startactivityforresult (New Intent (this, secondactivity.class), request_code);// This method invokes an activity and waits for the result to be returned from this activity: Incoming intent object and request code (only an integer value that identifies the activity being called)
Self-defined Onactivityresult () method:
When an activity returns, you must call your own implementation of the Onactivityresult () method public void Onactivityresult (int requestcode, int resultcode, Intent data) {if (Requestcode = = Request_code) {//Test request code if (ResultCode = = RESULT_OK) {//test result code Toast.maketext (this, Data.getdata (). toString (), Toast.length_short). Show ();}}}
4, operation, the effect is as follows:
Click the button:
Enter a name and click OK:
Summarize:
1, call Onstartactivityforresult () method and set the request code;
2, in the called activity, through the intent object callback data and set the result code (SetData () method and Setresult () method);
3, in the call activity, the definition of Onactivityresult () method, first check the request code and the result code, and then other processing.