Android learning notes-sample code for using Intent to pass values in Activity

Source: Internet
Author: User

Intent, also known as Intent, is a runtime binding mechanism. It can link two different components (Activity, Service, BroadcastReceiver) while the program is running ). With Intent, the program can express a request or willingness to Android. Android will select an appropriate component for the request based on the desired content.

The communication between these components is mainly completed with Intent assistance. Intent describes the actions, actions involving data, and additional data of an application. Android identifies the corresponding components based on the description of the Intent, pass Intent to the called component and complete the call of the component. Therefore, Intent acts as a media intermediary here, providing information about component calls to each other to decouple callers from callers.
To request an Activity through Intent, you must add a tag configuration for the requested Activity in the AndroidManifest. xml file. Otherwise, an error will occur.

Intent generally contains two main information: action and data.
Action: indicates the action of this Intent operation.
Data: indicates the data involved in this action.

The following example shows how to use Intent to direct a new Activity and transmit data. This program only redirects between two pages, but creates a new Activity each time it redirects. Therefore, after startActivity (), you must call finish () to destroy the current Activity. if the Activity is not destroyed, after multiple jumps, multiple activities are stored in the Activity stack of the program. Click the return button of the device and you will find that the Activity is always backward.

Main steps:
Create an Android project, add the layout file other. xml, and add the Activity class otherActivity. class to accept Intent and display other. xml.
In the MainActivity class, declare an Intent class and specify the source and target through the Intent constructor.
After obtaining the Intent, use the Intent. putExtra () method to pass in data to it.
Call Activity. startActivity to start the Intent.
In the otherActivity class, use Activity. getIntent () to obtain the Intent of the current Activity.
After obtaining the Intent, use the Intent. getXxxExtra () method to obtain the stored data.
Configure the otherActivity node in AndroidManifest. xml.

Sample Code
Step 2-3:Copy codeThe Code is as follows: public class MainActivity extends Activity {
Private TextView textView;
Private Button btn;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
TextView = (TextView) findViewById (R. id. textView1 );
Btn = (Button) findViewById (R. id. button1 );
Btn. setOnClickListener (new View. OnClickListener (){
@ Override
Public void onClick (View v ){
// Intent constructor: Intent source; Intent purpose.
Intent intent = new Intent (MainActivity. this, otherActivity. class );
Intent. putExtra ("data", "Current page 2, information from page 1 ");
StartActivity (intent); // start Activity
Finish ();
}
});
}
}

Step 4-5:Copy codeThe Code is as follows: public class otherActivity extends Activity {
Private Button btn;
Private TextView textView;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
// TODO Auto-generated method stub
Super. onCreate (savedInstanceState );
SetContentView (R. layout. other );
TextView = (TextView) findViewById (R. id. textView2 );
Btn = (Button) findViewById (R. id. button2 );
// Use Activity. getIntent () to obtain the Intent received on the current page.
Intent intent = getIntent ();
// The getXxxExtra method is used to obtain the data passed by Intent.
String msg = intent. getStringExtra ("data ");
TextView. setText (msg );
Btn. setOnClickListener (new View. OnClickListener (){
@ Override
Public void onClick (View v ){
Intent intent = new Intent (otherActivity. this, MainActivity. class );
StartActivity (intent );
Finish ();
}
});
}
}

Step 7:Copy codeThe Code is as follows: <application
Android: allowBackup = "true"
Android: icon = "@ drawable/ic_launcher"
Android: label = "@ string/app_name"
Android: theme = "@ style/AppTheme">
<Activity
Android: name = "cn. bgxt. IntentForAc. MainActivity"
Android: label = "@ string/app_name">
<Intent-filter>
<Action android: name = "android. intent. action. MAIN"/>
<Category android: name = "android. intent. category. LAUNCHER"/>
</Intent-filter>
</Activity>
<Activity android: name = ". otherActivity"/>
</Application>

Return data from Activity
The above example only describes how to transmit data to an Activity through Intent. However, in practice, not only data needs to be transmitted to the Activity, but also data needs to be returned from the Activity, although the returned data is similar to the transmitted data, there are some differences.
The main differences are as follows:
To transmit data, you must use the Activity. startActivityForResult () method to start the Activity. You must pass the request code instead of Activity. startActivity ().
When returning data, call Activity. setResult () to set the returned Intent and return code.
The onActivityResult () method of the source Activity needs to be rewritten to accept the returned Intent. The onActivityResult () method will judge the Request Code and response code.
An example shows how to return data from an Activity. There are two activities in this program. In MainActivity, enter the number of addition operations, jump to otherActivity, enter the calculation result, and click return to output the calculation result to MainActivity.
Sample Code
MainActivity:Copy codeThe Code is as follows: public class MainActivity extends Activity {
Private EditText one, two, result;
Private Button btn;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. activity_main );
One = (EditText) findViewById (R. id. one );
Two = (EditText) findViewById (R. id. two );
Result = (EditText) findViewById (R. id. result );
Btn = (Button) findViewById (R. id. btnGo );
Btn. setOnClickListener (new View. OnClickListener (){
@ Override
Public void onClick (View v ){
// TODO Auto-generated method stub
Int ione = Integer. parseInt (one. getText (). toString ());
Int itwo = Integer. parseInt (two. getText (). toString ());
Intent intent = new Intent (MainActivity. this, otherActivity. class );
Intent. putExtra ("one", ione );
Intent. putExtra ("two", itwo );
// Start the Activity that requires listening for the returned value, and set the Request Code: requestCode
StartActivityForResult (intent, 1 );
}
});
}
@ Override
Protected void onActivityResult (int requestCode, int resultCode, Intent data ){
Super. onActivityResult (requestCode, resultCode, data );
// This method is returned when data is returned in otherActivity.
// RequestCode and resultCode must be consistent with the value passed in when startActivityForResult () is requested and setResult () is returned.
If (requestCode = 1 & resultCode = 2)
{
Int three = data. getIntExtra ("three", 0 );
Result. setText (String. valueOf (three ));
}
}
@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
// Inflate the menu; this adds items to the action bar if it is present.
GetMenuInflater (). inflate (R. menu. main, menu );
Return true;
}
}

OtherActivity:Copy codeThe Code is as follows: public class otherActivity extends Activity {
TextView tvShow;
EditText etResult;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. other );
TvShow = (TextView) findViewById (R. id. tvShow );
EtResult = (EditText) findViewById (R. id. etResult );
Intent intent = getIntent ();
Int a = intent. getIntExtra ("one", 0 );
Int B = intent. getIntExtra ("two", 0 );
TvShow. setText (a + "+" + B + "=" + "? ");
Button btnResult = (Button) findViewById (R. id. btnReturn );
BtnResult. setOnClickListener (new View. OnClickListener (){
@ Override
Public void onClick (View v ){
// Declare a new Intent to store the stored data
Intent I = new Intent ();
Int result = Integer. parseInt (etResult. getText (). toString ());
I. putExtra ("three", result );
SetResult (2, I); // set resultCode, which can be obtained in onActivityResult ()
Finish (); // end the lifecycle of the current Activity after use
}
});
}
}

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.