The StartActivity () method can invoke another activity, but this method does not return a result to the current activity. For example, if you have an activity that prompts the user for a username and password, and the information entered by the user needs to be "returned" to the activity of the input information, the Startactivityforresult () method is required.
1. Code in the Secondactivity.xml.
<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertic Al "> <textview android:layout_width=" fill_parent "android:layout_height=" W Rap_content "android:text=" This is the Second activity!/> <textview Id: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_par" Ent "android:layout_height=" wrap_content "/> <button android:id=" @+id/btn_o K "android:layout_width=" fill_parent "android:layout_height=" wrap_content "android:onclick=" OnC Lick "android:text="OK"/> </LinearLayout>
2. Code in the Secondactivity.java.
public class
Secondactivity extends activity {
@Override public
void OnCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.secondactivity);
}
public void OnClick (view view) {
Intent data = new Intent ();
---Get the edittext view---
edittext txt_username = (edittext) Findviewbyid (r.id.txt_username);
---Set the data to pass---
data.setdata (uri.parse () (Txt_username.gettext (). toString ()));
Setresult (RESULT_OK, data);
---Closes the activity---
finish ();
}
3. Code in the Usingintentactivity.java.
public class Usingintentactivity extends activity {int request_code = 1; /** called the activity is a.
* * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main); public void OnClick (view view) {//StartActivity (New Intent ("Net.horsttnann.s
Econdactivity "));
or//StartActivity (new Intent (this, secondactivity.class));
Startactivityforresult (New Intent ("Net.horsttnann.SecondActivity"), Request_code); } public void Onactivityresult (int requestcode, int resultcode, Intent data) {I F (Requestcode = = Request_code) {if (ResultCode = = RESULT_OK) {Toast.maketext (this
, Data.getdata (). toString (), Toast.length_short). Show (); }
}
}
}