Getting Started with Android (ii) Activity-toast, Intent

Source: Internet
Author: User

Original link: http://www.orlion.ga/427/

First, hide the title of activity

Enter Requestwindowfeature (window.feature_no_title) in the OnCreate () method of the activity's Java code, as follows:

@Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature ( Window.feature_no_title); Setcontentview (r.layout.first_layout);}

Ii. using toasts in activity

First, bind the button to a point-and-click event, and then pop the toast when the button is clicked:

@Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature ( Window.feature_no_title); Setcontentview (r.layout.first_layout);//Click the button to eject Toastbutton button1 = (Button) Findviewbyid (r.id.button_1); Button1.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) { Toast.maketext (Firstactivity.this, "You chick button 1", Toast.length_short). Show (); }});}

Explanation: In the activity, you can get to the element defined in the layout file through the Findviewbyid () method, here we pass in r.id.button_1, to get the instance of the button, this value is just in First_layout.xml through Android: The id attribute is specified. The Findviewbyid () method returns a View object, which we need to transform downward to turn it into a button object. After getting an instance of the button, we register a listener for the button by calling the Setonclicklistener () method, and the OnClick () method in the listener is executed when the button is clicked. Therefore, the ability to eject a toast is, of course, written in the Nclick () method.

A toast is very simple to use, creating a Toast object with a static method Maketext () and then calling Show () to display the toast. It is important to note that the Maketext () method needs to pass in three parameters. The first parameter is the context, which is a request for a toast, because the activity itself is a contextual object, so it can be passed directly to Firstactivity.this. The second parameter is the text content of the toast display, the third parameter is the length of the toast display, and there are two built-in constants to choose Toast.length_short and Toast.length_long.

If you need to reference an ID in XML, use the @id/id_name syntax, and if you need to

To define an ID, you use the @+id/id_name syntax.

Third, the use of intent

How can I jump from the main activity to other activities? Let's take a look at it now.

1. Using explicit intent

Create a second activity in the Activitytest project. Create a new Second_layout.xml layout file with the following code:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " ><button android:id= "@+id/button_2" android:layout_width= "match_parent" android:layout_height= "wrap_content "Android:text=" button 2 "/></linearlayout>

The new activity secondactivity inherits from activity with the following code:

Package Ga.orlion.activitydemo1;import Android.app.activity;import Android.os.bundle;import Android.view.Window; public class Secondactivity extends Activity {@Overridepublic void onCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); requestwindowfeature (Window.feature_no_title); Setcontentview (R.layout.second_layout);}}

Finally, the secondactivity is registered in Androidmanifest.xml.

<activity android:name= ". Secondactivity "> </activity>

Since secondactivity is not a master activity, there is no need to configure the contents of the <intent-filter> tag, and the code to register the activity is much simpler. Now that the second activity has been created, the remaining question is how to start the second activity, where we need to introduce a new concept, Intent.

Intent is an important way to interact with components in an Android program, not only to indicate what actions the current component wants to perform, but also to pass data between different components. Intent generally can be used to launch activities, start services, and send broadcasts and other scenarios, due to the concept of service, broadcast and so on you have not yet been involved, this chapter our eyes are undoubtedly locked in the start-up activities above. The usage of Intent can be broadly divided into two types, explicit Intent and implicit Intent, and let's take a look at how explicit Intent is used.

Intent has multiple overloads of constructors, one of which is Intent (Context packagecontext, class<?> CLS). This constructor receives two parameters, the first parameter context requires a start-up activity, and the second class specifies the target activity that you want to start, and this constructor allows you to construct the "intent" of the intent. Then how should we use this intent? The activity class provides a startactivity () method that is specifically used to initiate the activity, which receives a intent parameter, where we will build the intent incoming startactivity ()

method to start the target activity. Modify the Click event for the button in Firstactivity, as shown in the following code:

Button1.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Intent Intent = NE        W Intent (Firstactivity.this, Secondactivity.class);    StartActivity (Intent); }});

We first constructed a intent, passed in the Firstactivity.this as the context, passed in the Secondactivity.class as the target activity, so our "intent" is very obvious, that Firstactivity this activity on the basis of opening secondactivity this activity. The Intent is then executed through the StartActivity () method. Re-run the program, click on the Firstactivity interface button We have successfully launched secondactivity this activity. What if you want to go back to the last event? Very simply, press the back key to destroy the current activity and return to the previous activity. Using this method to start the activity, Intent's "intent" is very obvious, so we call it an explicit Intent.

2. Using implicit intent

Implicit Intent is a lot more subtle than explicit Intent, and it does not clearly indicate which of the jobs we want to start

A series of more abstract action and category information, which is then referred to the system to analyze the intent and help us find the right activity to start. What is the right activity? In simple terms, we can respond to this implicit intent activity, so what kind of implicit intent can secondactivity respond to now? Well, it seems like nothing can be answered, but it will be soon. By configuring <intent-filter> Under the <activity> tab, you can specify the action and category that the current activity responds to, open androidmanifest.xml, and add the following code:

<activity android:name= ".         Secondactivity "> <intent-filter> <action android:name=" Com.example.activitytest.ACTION_START "/> <category android:name= "Android.intent.category.DEFAULT"/> </intent-filter></activity>

In the <action> tab we indicate that the current activity can respond to the Com.example.activitytest.ACTION_START action, while the <category> tag contains some additional information A more precise indication of the category that may be present in the intent that the current activity can respond to. This activity should Intent only if the contents of <action> and <category> match the action and category specified in Intent. Modify the Click event for the button in Firstactivity, as shown in the following code:

Button1.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Intent Intent = NE        W Intent ("Com.example.activitytest.ACTION_START");    StartActivity (Intent); }});

As you can see, we use another constructor of intent, which directly passes in the action string, indicating that we want to start an activity that responds to the action of Com.example.activitytest.ACTION_START. Isn't that the first time you want <action> and <category> to be able to respond in a match? How can you not see where there is a designated category? This is because Android.intent.category.DEFAULT is a default category that automatically adds the category to intent when the StartActivity () method is called. Re-run the program, click on the Firstactivity interface button, the same successful start secondactivity.

3. Transfer data using intent

Intent can also pass data at the start of the activity, let's take a look. The idea of passing data when starting an activity is simple, intent provides a series of overloads of the PutExtra () method that can temporarily present the data we want to pass in intent, and once another activity is started, it is only necessary to remove the data from the intent. For example, there is a string in firstactivity, and now you want to pass the string to secondactivity, you can write it like this:

Button1.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {String data = "Hel        Lo secondactivity ";        Intent Intent = new Intent (firstactivity.this, Secondactivity.class);        Intent.putextra ("Extra_data", data);    StartActivity (Intent); }});

Here we still use an explicit intent to start secondactivity and pass a string through the PutExtra () method. Note here that the Putextra () method receives two parameters, the first parameter is the key, which is used to fetch the value from the intent, and the second parameter is the data that is actually being passed. We then take out the data passed in the Secondactivity and print it out, as shown in the code below:

public class secondactivity extends activity {      @Override     protected void oncreate (bundle  savedinstancestate)  {        super.oncreate (savedInstanceState);         requestwindowfeature (Window.feature_no_title);         setcontentview (r.layout.second_layout);         intent intent = getintent ();         String data = intent.getstringextra ("Extra_data");        &NBSP;LOG.D ("Secondactivity",  data);     }} 

The Getintent () method can be used first to get the Intent to start secondactivity, and then call the Getstringextra () method, passing in the corresponding key value, you can get the data passed. This is because we are passing strings, so we use the Getstringextra () method to get the data passed, and if we pass the integer data, the Getintextra () method is used, the Boolean data is passed, and the Getbooleanextra () method is used. And so on

4. Return data to previous activity

Now that you can pass data to the next activity, can you not return the data to the previous activity? The answer is yes. However, the only way to return to the previous activity is to press the back key, and no one is used to start the activity intent to pass the data. By reviewing the documentation you will find that there is also a Startactivityforresult () method in activity that is also used to initiate activities, but this method expects to return a result to the previous activity when the activity is destroyed. There is no doubt that this is what we need. The Startactivityforresult () method receives two parameters, the first parameter is Intent, and the second parameter is the request code, which is used to determine the source of the data in subsequent callbacks. Let's do the actual combat. Modify the Click event for the button in Firstactivity, as shown in the following code:

Button1.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Intent Intent = NE        W Intent (Firstactivity.this, Secondactivity.class);    Startactivityforresult (Intent, 1); }});

Here we use the Startactivityforresult () method to start the secondactivity, as long as the request code is a unique value can be, here passed 1. Next we register the click event with the button in secondactivity and add the logic to return the data in the Click event, as shown in the code below:

public class secondactivity extends activity {     @Override      protected void oncreate (bundle savedinstancestate)  {         super.oncreate (savedinstancestate);         requestwindowfeature (Window.feature_no_title);         Setcontentview (r.layout.second_layout);         button button2  =  (Button)  findviewbyid (r.id.button_2);         Button2.setonclicklistener (New onclicklistener ()  {              @Override              Public void onclick (VIEW&NBSP;V)  {                 intent&nBsp;intent = new intent ();                 intent.putextra ("Data_return",  "hello firstactivity");                 setresult (RESULT_OK,  Intent);                 finish ();            }         });     }}

     as you can see, we're still building a Intent, but this Intent is just for passing data, and it doesn't specify any "intent." The data to be passed is then stored in intent and the Setresult () method is called. This method is very important and is specifically used to return data to the previous activity. The Setresult () method receives two parameters, the first parameter is used to return the processing result to the previous activity, typically only the RESULT_OK or result_canceled values are used, the second parameter is to pass the intent with the data back, and then call the finish () method to destroy the current activity. Since we are using the Startactivityforresult () method to start Secondactivity, the Onactivityresult () method of the previous activity is recalled after Secondactivity is destroyed, so we need to This method is overridden in firstactivity to get the returned data as follows:

 @Overrideprotected  void onactivityresult (Int requestcode,  int resultcode, intent data)  {    switch  (Requestcode)  {    case 1:        if  (ResultCode &NBSP;==&NBSP;RESULT_OK)  {            string  returneddata = data.getstringextra ("Data_return");        &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.D ("Firstactivity",  returneddata);         }        break;    default:     }} 

The Onactivityresult () method has three parameters, the first parameter Requestcode, which is the request code that we passed in when the activity was started. The second parameter, ResultCode, is the result of the processing we passed in when we returned the data. The third parameter, data, is the Intent that carries the returned data. Since it is possible to invoke the Startactivityforresult () method in an activity to initiate many different activities, the data returned by each activity will be called back to the Onactivityresult () method, so the first thing we need to do is to check Requestcode values to determine the source of the data. After determining that the data is returned from secondactivity, we then use the value of ResultCode to determine whether the processing result is successful. Finally, the value is taken from data and printed out, which completes the work of returning data to an activity.

If the user is not in the secondactivity by clicking the button, but by pressing the back key to return to firstactivity, so that the data can not be returned? Yes, but this is a good thing to do, and we can solve this problem by overriding the Onbackpressed () method, as shown in the following code:

@Overridepublic void onbackpressed () {Intent Intent = new Intent ();    Intent.putextra ("Data_return", "Hello firstactivity");    Setresult (RESULT_OK, intent); Finish ();}

Getting Started with Android (ii) Activity-toast, Intent

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.