Android beginners (2) Activity-Toast, Intent, intentservicetoast

Source: Internet
Author: User

Android beginners (2) Activity-Toast, Intent, intentservicetoast

Link: http://www.orlion.ga/427/

1. Hide the title of an activity

In the onCreate () method of the java code of the activity, enter requestWindowFeature (Window. FEATURE_NO_TITLE); as follows:

@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.first_layout);}

2. Use Toast in Activity

First, bind a click event to the button, and then the toast will pop up 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 bring up 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 an activity, you can use the findViewById () method to obtain the elements defined in the layout file. Here we pass in the R. id. button_1 to get the button instance. This value was just specified in first_layout.xml using the android: id attribute. The findViewById () method returns a View object, which needs to be transformed down to a Button object. After obtaining the instance of the button, call the setOnClickListener () method to register a listener for the button. When you click the button, The onClick () method in the listener is executed. Therefore, the pop-up Toast function must be compiled in the nClick () method.

Toast usage is very simple. You can use the static method makeText () to create a Toast object, and then call show () to display Toast. Note that the makeText () method requires three parameters. The first parameter is Context, which is the Context required by Toast. Because the activity itself is a Context object, you can directly input FirstActivity. this here. The second parameter is the text content displayed by Toast, and the third parameter is the display duration of Toast. Two built-in constants can be Toast. LENGTH_SHORT and Toast. LENGTH_LONG.

 

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

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

 

3. Use Intent

How can I jump from a primary activity to another activity? Let's take a look at it now.

1. Use an explicit Intent

Create another activity in the ActivityTest project. Create a second_layout.xml layout file. The Code is as follows:

<?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 code for creating a SecondActivity inherited from the Activity is as follows:

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, register SecondActivity in AndroidManifest. xml.

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

Because SecondActivity is not a primary activity, you do not need to configure the content in the <intent-filter> label. The code for registering an activity is much simpler. Now that the second activity has been created, the remaining question is how to start the second activity. here we need to introduce a new concept, Intent.

Intent is an important way to interact with each component in the Android program. It not only specifies the action to be executed by the current component, but also transmits data between different components. Intent can be used to start activities, start services, send broadcasts, and other scenarios. You have not yet covered the concepts of services, broadcasts, and so on, in this chapter, our eyes are undoubtedly on the startup activities. Intent usage can be roughly divided into two types: explicit Intent and implicit Intent. Let's first look at how to use the explicit Intent.

Intent has multiple constructor overloading, one of which is Intent (Context packageContext, Class <?> Cls ). This constructor receives two parameters. The first parameter Context requires a Context for the startup activity, and the second parameter Class specifies the target activity to be started, this constructor can be used to construct the Intent "Intent ". Then how should we use this Intent? The Activity class provides a startActivity () method, which is used to start an Activity. It receives an Intent parameter. Here we pass the constructed Intent to startActivity ()

Method to start the target activity. Modify the Click Event of the button in FirstActivity. The Code is as follows:

button1.setOnClickListener(new OnClickListener() {    @Override    public void onClick(View v) {        Intent intent = new Intent(FirstActivity.this, SecondActivity.class);        startActivity(intent);    }});

We first constructed an Intent and passed in FirstActivity. this is used as the context to pass in SecondActivity. class as the target activity, so our "intention" is very obvious, that is, to open the SecondActivity activity on the basis of the FirstActivity. Execute the Intent using startActivity. Run the program again. On the FirstActivity page, click the button and we have successfully started the SecondActivity. What if you want to return to the previous activity? Simply press the Back key to destroy the current activity and return to the previous activity. In this way, Intent's "Intent" is very obvious, so we call it an explicit Intent.

2. Use implicit Intent

Compared with the explicit Intent, the implicit Intent is much more subtle, and it does not explicitly indicate which live activity we want to start.

Instead, it specifies a series of more abstract information such as action and category, and then analyzes the Intent by the system and helps us find the appropriate activity to start. What is an appropriate activity? Simply put, it can respond to our implicit Intent activity. So what kind of implicit Intent can SecondActivity respond to now? Well, now it seems that nothing can respond, but it will soon be there. By configuring the <intent-filter> content under the <activity> tag, you can specify the actions and category that the current activity can respond 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> tag, we specify that the current activity can respond to com. example. activitytest. the ACTION_START action, and the <category> tag contains additional information, which more accurately specifies the category that may be included in the Intent that the current activity can respond. Only when the content in <action> and <category> matches the action and category specified in the Intent at the same time can this activity respond to this Intent. Modify the Click Event of the button in FirstActivity. The Code is as follows:

button1.setOnClickListener(new OnClickListener() {    @Override    public void onClick(View v) {        Intent intent = new Intent("com.example.activitytest.ACTION_START");        startActivity(intent);    }});

We can see that another Intent constructor is used to directly upload the action string, indicating that we want to start the activity that can respond to the action com. example. activitytest. ACTION_START. Didn't we say that <action> and <category> must be matched at the same time to respond? Why can't I see a specified category? This is because android. intent. category. DEFAULT is a DEFAULT category, which is automatically added to the Intent when the startActivity () method is called. Run the program again. click the button on the FirstActivity interface to start SecondActivity again.

 

3. Use Intent to transmit data

Intent can also transmit data when starting the activity. Let's take a look. The idea of transferring data when starting an activity is very simple. Intent provides a series of putExtra () Methods to store the data we want to transfer in Intent. After starting another activity, you only need to extract the data from Intent. For example, if there is a string in FirstActivity and you want to pass it to SecondActivity, you can write it as follows:

button1.setOnClickListener(new OnClickListener() {    @Override    public void onClick(View v) {        String data = "Hello SecondActivity";        Intent intent = new Intent(FirstActivity.this, SecondActivity.class);        intent.putExtra("extra_data", data);        startActivity(intent);    }});

Here we use the explicit Intent method to start SecondActivity and pass a string through the putExtra () method. Note that the putExtra () method receives two parameters. The first parameter is the key, which is used to take values from the Intent. The second parameter is the data to be passed. In SecondActivity, we extract and print the transmitted data. The Code is as follows:

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");        Log.d("SecondActivity", data);    }}

First, you can use the getIntent () method to obtain the Intent used to start SecondActivity, call the getStringExtra () method, and input the corresponding key value to obtain the transmitted data. The getStringExtra () method is used to obtain the passed data because the string is passed. If the passed data is an integer, The getIntExtra () method is used, if boolean data is passed, use the getBooleanExtra () method, and so on.

4. return data to the previous activity

Since data can be transmitted to the next activity, CAN data be returned to the previous activity? The answer is yes. However, the difference is that you only need to press the Back key to return the previous activity, and no Intent is used to start the activity to transmit data. After reading the document, you will find that the startActivityForResult () method in the Activity is also used to start the Activity, but this method is expected 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 data source in the subsequent callback. The Code is as follows:

button1.setOnClickListener(new OnClickListener() {    @Override    public void onClick(View v) {        Intent intent = new Intent(FirstActivity.this, SecondActivity.class);        startActivityForResult(intent, 1);    }});

Here we use the startActivityForResult () method to start SecondActivity. The request code can be a unique value. Here 1 is passed in. Next, register the click event for the button in SecondActivity, and add the returned data logic in the click event. The Code is as follows:

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 v) {                Intent intent = new Intent();                intent.putExtra("data_return", "Hello FirstActivity");                setResult(RESULT_OK, intent);                finish();            }        });    }}

We can see that we have built an Intent, but this Intent is only used to transmit data, and it does not specify any "Intent ". Then, the data to be passed is stored in the Intent, and the setResult () method is called. This method is very important and is used to return data to an activity. The setResult () method receives two parameters. The first parameter is used to return the processing result to an activity. Generally, only the values RESULT_ OK or RESULT_CANCELED are used, the second parameter is to pass the Intent with data back, and then call the finish () method to destroy the current activity. The startActivityForResult () method is used to start SecondActivity. After SecondActivity is destroyed, the onActivityResult () method of the previous activity is called back, therefore, we need to rewrite this method in FirstActivity to obtain the returned data, as shown below:

@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {    switch (requestCode) {    case 1:        if (resultCode == RESULT_OK) {            String returnedData = data.getStringExtra("data_return");            Log.d("FirstActivity", returnedData);        }        break;    default:    }}

The onActivityResult () method has three parameters. The first parameter is requestCode, which is the request code we passed when starting the activity. The second parameter, resultCode, is the processing result we pass in when returning data. The third parameter data carries the Intent of the returned data. Because the startActivityForResult () method may be called in an activity to start many different activities, the data returned by each activity will be called back to the onActivityResult () method, therefore, we must first check the value of requestCode to determine the data source. After confirming that the data is returned from SecondActivity, we can use the resultCode value to determine whether the processing result is successful. Finally, the value is printed out from the data, and the data returned from the previous activity is completed.

If the user does not click the button in SecondActivity, but presses the Back key to return to FirstActivity, then the data cannot be returned? Yes, but this situation is still well handled. We can solve this problem by rewriting onBackPressed (). The Code is as follows:

@Overridepublic void onBackPressed() {    Intent intent = new Intent();    intent.putExtra("data_return", "Hello FirstActivity");    setResult(RESULT_OK, intent);    finish();}

Related Article

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.