Andoid intent learn to pass data between activities

Source: Internet
Author: User

Intent is a runtime binding (Run-time binding) mechanism that connects two different components during a program's run. With intent, your program can express some kind of request or intention to Android, and Android will select the appropriate component to complete the request based on the intended content.

1. Use intent to pass data down an activity

    1. Add a button to the Activity_main.xml
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools" android:layout_width= "Match_parent"Android:layout_height= "Match_parent" android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Android:paddingbottom= "@dimen/activity_vertical_margin" tools:context= ". Mainactivity "> <Button Android:id= "@+id/btn1"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "@string/btn1"/></linearlayout>

2. Write a listener event for Button1 in Mainactivity

(Button) Findviewbyid (R.ID.BTN1). Setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {/*use intent to pass data to the next activity*/String Data= "Hello World!!!"; Intent Intent=NewIntent (); Intent.setclass (mainactivity. This, Secondactivity.class); Intent.putextra ("Extra_data", data); StartActivity (intent);});

3. Create a new secondactivity to receive data from Mainactivity

@Override     protected void onCreate (Bundle savedinstancestate) {        super. OnCreate (savedinstancestate);        Requestwindowfeature (window.feature_no_title);        Setcontentview (R.layout.activity_second);         /*         use Intent to pass data to the         next activity *        /= Getintent      (); = Intent.getstringextra ("Extra_data");     Toast.maketext (secondactivity.  This , Data,toast.length_short). Show ();}

2. Use intent to return data to the previous activity

1. Add a Button2 in secondactivity

<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools" android:layout_width= "Match_parent"Android:layout_height= "Match_parent" android:paddingleft= "@dimen/activity_horizontal_margin"Android:paddingright= "@dimen/activity_horizontal_margin"Android:paddingtop= "@dimen/activity_vertical_margin"Android:paddingbottom= "@dimen/activity_vertical_margin"android:orientation= "Vertical"Tools:context= "Com.tony.intenttest.SecondActivity" > <Button Android:id= "@+id/btn2"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "@string/btn2"/></linearlayout>

2. Write a listener event for Button1 in Mainactivity

 Public classMainactivityextendsActivity {PrivateButton btn1; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Requestwindowfeature (Window.feature_no_title);        Setcontentview (R.layout.activity_main); BTN1=(Button) Findviewbyid (R.ID.BTN1); Btn1.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {/*use intent to return data to the previous activity*/Intent Intent=NewIntent (mainactivity. This, Secondactivity.class); Startactivityforresult (Intent,1);    }        }); }

Note: the Startactivityforresult () method receives another parameter, the first parameter is intent, the second parameter is the request code (the request code as long as it is a unique value), used to determine the source of the data in subsequent callbacks.

3. Register a click event for Button2 in Secondactivity

 Public classSecondactivityextendsActivity {PrivateButton btn2; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Requestwindowfeature (Window.feature_no_title);        Setcontentview (R.layout.activity_second); /*use intent to return data to the previous activity*/btn2=(Button) Findviewbyid (R.ID.BTN2); Btn2.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {Intent Intent=NewIntent (); Intent.putextra ("Return_data", "Hello mainactivity!!!");                Setresult (result_ok,intent);            Finish ();    }        }); }        /*The onbackpressed () method is called if the return key is pressed (the back key)*/@Override Public voidonbackpressed () {Intent Intent=NewIntent (); Intent.putextra ("Return_data", "Hello mainactivity!!!");        Setresult (result_ok,intent);    Finish (); }}

Note: the PutExtra () method receives two parameters, the first parameter is the key, which is used for subsequent values from the intent, and the second parameter is the data to be passed.

Here again a intent is built, but this intent is only used to pass data, it does not specify any "intent". The data to be passed is then placed in the intent and called the Setresult () method.

The Setresult () method receives two parameters, the first parameter is used to return processing results to the previous activity, typically only RESULT_OK and result_cancled are used, the second parameter is to pass the intent with the data back, and then call Finish () Method destroys the current activity.

4. Receive data in Mainactivity, overriding the Onactivityresult () method.

@Overrideprotected voidOnactivityresult (intRequestcode,intResultCode, Intent data) {        Switch(requestcode) { Case1:                if(ResultCode = =RESULT_OK) {String Returneddata= Data.getstringextra ("Return_data"); LOG.D ("Tag", Returneddata); }                 Break; default:        }    }

Note: Because the Startactivityforresult () method is used to start secondactivity, the Onactivityresult () method of the previous activity is recalled after Secondactivity is destroyed, so In mainactivity

To override the Onactivityresult () method.

The Onactivityresult () method has three parameters, the first parameter Requestcode, which is the incoming request code in the start activity, and the second parameter ResultCode, which is the result of the processing we passed in when we returned the data. The third parameter, data, is the intent that the carrier returns.

Since the Startactivityforresult () method may be called in an activity to initiate many different activities, the data returned by each activity will be recalled to the Onactivityresult () method. Therefore, to pass the check

Requestcode value to determine the data source, determines whether the data is returned from Secondactivity, after the value of the ResultCode to determine the success of the processing results.

Andoid intent learn to pass data between activities

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.