1. Use the project created in the previous article to add the text box and button to the Secondactivity.xml file, such as 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 to the Secondactivity.java file, such as the following code:
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 in the Mainactivity.java file? For example, the following code:
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)
Custom 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, implementation, effects such as the following:
Click 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 invocation activity, the custom Onactivityresult () method, first verifies the request code and the result code, then carries on the other processing.