Create jump and pass value for Android development activity

Source: Internet
Author: User

There are four components in the Android system: activity, service, broadcast receiver (broadcast reciver) and Content provider (contents Provider). Today's introduction is one of the four components of Android development:Activity, the other three components are introduced later. The activity in Android, if you've developed iOS, issimilar to Viewcontroller (View Controller) in iOS. What you can see in the app is in the activity. Activity is an important thing for Android to develop and an entry point for user interaction and data. This blog to introduce the content is the creation of activities, activities of jump and value of the pass.

Viewcontroller in iOS also has its own life cycle, it is necessary to understand the life cycle of activity or viewcontroller, so that you can figure out when to do something about iOS development, please read the previous blog: my iOS Development series blog and my objective-c series articles . Don't say a word, the activity is going to debut.

Using Android Studio to create an Android Add New Activity Project (step, see the previous blog), in this project there will be a blank Activity, and the blank The activity automatically adds a text View that says "Hello World" and runs the project to see Hello World in a white activity.

We put a new activity created in this project and then have Hello World Add a button and click the button to jump to the new activity we created. Click Back in the New button to return to the previous activity.

I. Creation of activity and component additions 

1. Create a blank Activity

In the file resource directory of Android Studio, select the package you want to create activity from, right-click Activities,->new, activity, here we choose blank activity , click here, and the action is as shown.

The following dialog box appears after clicking to create a new activity, which is our custom activity. Activity name: Name of the event, layout name: The name of the activity corresponding layout file, Titile: The name shown above the navigation bar. Menu Resource Name: the names of the XML configuration files for menus (detailed later), click Finishi.

When the activity is created, three files are generated in the resource directory, as shown in Java, the secondactivity file has the preceding "C" flag known as the Java class file, which is the source file for the activity. The activity_second.xml in the layout file is the layout file for the activity, where you can specify which controls to add to the activity, and you can control the style and position of those controls. The third is the menu under the menu_second.xml file, which is defined in the Navigation drop-down menu content, and later to show you.

2. Control Additions

Adding controls to the activity requires manipulating the XML file for the activity in our Layout folder. The next thing to do is to add a button to the layout file in the mainactivity, then get a button in the code, and listen for the button's click event, and the button clicks on the event trigger to pop up a prompt. Take a detailed look at how to add a control and listen to the control's events.

(1) Add button

Open the activity_main.xml layout file, switch to design mode, and in design mode you can create the control in a drag-and-drop manner, as well as position the control. A button is added below, and the text on the button is Showtoast (toast is the component used to display information in Android).

You can also switch to text mode to see the XML, the following large box is the content of the XML corresponding to the button we just dragged out, including layout-related information: The control of the width of the height, the left and right margin and so on, There are some properties of the control: the ID that is unique to the control, and the text that the control displays, and so on. Of course, if you know more about the properties of XML layouts, you can use pure code to declare and lay out your controls.

(2) Getting controls in code

After the above steps, a button has been declared and configured. If you want to use the control in your code, you first have to instantiate the control with the ID of the button above. The following code is added to the Oncreat () method in the Mainactivity file, about the OnCreate method, and the life cycle of the activity later is described in detail. In Java source code, you can instantiate the control specified in the layout file by Findviewbyid. The button above has the id "Myfirstbutton", so the method for instantiating the button is as follows:

        // get buttons        on the interface Button Myfirstbutton = (button) Findviewbyid (R.id.myfirstbutton);

After instantiating the button we need to listen for the click events of the buttons, which are used in a similar way to block callbacks in iOS. is to give the button a click button to execute the method. Clicking on the button executes the callback method below, and the content can be prompted with a toast.

 1  //  2  Myfirstbutton.setonclicklistener (new   View.onclicklistener () { 3  Span style= "color: #000000;" > @Override  4  public void   OnClick (View v) { 5  toast.maketext (mainactivity. This , "click Myfirstbutton" , Toast.length_long). Show ();  6   7
     }); 

After the above steps, click on the Showtoast button will prompt "Click Myfirstbutton" Content, below is the result of the execution:

Second, the activity between the jump and transfer value

In the above we have created a blank activity named Secondactivity, which has been shown to have a go Second activity button in Mainactivity, from the above running effect. She is used to jump to secondactivity, different activity see jump can pass value, also can return when return value, next introduce activity between jump and transfer value problem.

1. Jump to activity using intent

Intent is known as the "intent" in Android development, and it is not hard to understand the literal meaning of " where you are going". Intent is very similar to the Navigationcontroller (navigation Controller) in iOS development, but it's different. Navigationcontroller is a "stack" form of the container, the controller can be push or pop operation "into the stack" and "out of the stack", this into the stack and the operation of the stack is the view controller to switch operations. Intent implementation principle is the same, there is a stack, the content stored in this stack is a activity,activity of the start and finish operation corresponding to the stack of push and pop operations.

(1) Add a jump code to the click event of the "Go Second Activity" button, jump to Secondactiviy, the code below, the code below is placed in the OnCreate method. In the constructor for the intent class used below, the first parameter is the current activity, and the second parameter is the activity that will jump. The StartActivity method to start the intent, rather than start intent, rather than the current activity as a stack, the activity will be displayed on the top of the stack.

Button Gosecondactivitybutton =(Button) Findviewbyid (R.id.go_sceond_button); Gosecondactivitybutton.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {//Create a new intent (current activity, secondactivity) ===== Display IntentIntent Intent =NewIntent (mainactivity. This, Secondactivity.class); //Start Intentstartactivity (Intent); }        });

  

(2) If the value in the mainactivity is passed to the secondactivity to jump past, then the value can be passed through the Putextra method in the intent object. Adding the following code above the Code startactivity () method is to pass the value to the target activity. Data is a variable of type string, where the stored value is passed to the activity that is going to jump. The intent object is passed by calling Putextra, and the first parameter is a key that is worth the name, which is the value, and the key to get the corresponding value in the next activity.

1                 // Pass the value to the next activity 2                 String data = "I am the value passed in the last activity"; 3 4                 Intent.putextra ("Extra_data", data);

(3) In the new activity we need to get the values passed in TextView, and click on a Back button to return to the previous activity, the specific code is as follows. The code is placed in the OnCreate () method of the second activity. can be obtained through getintent to jump through that intent, in other words to get the current navigation stack. Once the intent object is obtained, a corresponding key is passed through the Getstringextra () method, and the value is obtained by this key. Because the values we pass in are of type string, with Getstringextra (), different types of values correspond to different methods. The obtained value is then displayed on the TextView. Then click button to return. The finish () method in the button ends the current activity and automatically returns to the previous activity. TextView and buttons are also fetched by drag-and-drop, and the event is processed and assigned by ID.

1         //gets the value that was passed from the previous activity.2Intent Intent =getintent ();3String data = Intent.getstringextra ("Extra_data");4         5         //displays the obtained value on the TextView6TextView Datatextview =(TextView) Findviewbyid (R.id.data_text_view);7 datatextview.settext (data);8 9         //Click button to return to the previous activityTenButton Backbutton =(Button) Findviewbyid (R.id.bank_button); OneBackbutton.setonclicklistener (NewView.onclicklistener () { A @Override -              Public voidOnClick (View v) { - finish (); the             } -});

After the above steps, the final effect is as follows, clicking the Go Second activity button in mainactivity jumps to the second activity, and the value passed in the first page is displayed in the second activity. Clicking the Back button in Secondactivity will execute the finish () method to return to the previous activity.

2. Use intent to turn on system functions

You can open certain functions of the system in terms of protocol, such as opening the system's browser, the system's dial-up keyboard, etc. The same is true for iOS, which simply invokes system functionality by opening certain protocols, such as tel://dialing protocols, through application objects. These operations can also be done through the intent object in the Android system.

(1) Call the browser to open the link code below, the code below is the call Browser open link. Action_view is more intelligent, he will be through the user's incoming data to open the appropriate application, the following is through the SetData incoming URL, so it will call the browser, if the incoming tel:10010, will call the dial disk.

        Button Openbaidubutton = (Button) Findviewbyid (R.id.open_baidu_button);        Openbaidubutton.setonclicklistener (new  View.onclicklistener () {            @Override              Publicvoid  OnClick (View v) {                // call local browser to open URL                new Intent (intent.action_view);                Intent.setdata (Uri.parse ("http://www.baidu.com"));                StartActivity (intent);            }        });

(2) Call dial you can change the incoming data by the above method, but you can also call the dial by intent.action_dial, the specific code is as follows:

1Button Telphonebutton =(Button) Findviewbyid (r.id.tel_number);2Telphonebutton.setonclicklistener (NewView.onclicklistener () {3 @Override4              Public voidOnClick (View v) {5Intent Intent =NewIntent (intent.action_dial);6Intent.setdata (Uri.parse ("tel:10010"));7 startactivity (intent);8             }9});

Click on the top two buttons the first one will open the URL through the browser, the second will open the dial, the effect is as follows.



3. Get the value from the activity in the return

From the example above, we can transfer values from one activity to the next. The next thing to do is to get the value from the returned page. This kind of transmission is also done through intent. We add a button "Go third activity" in Mainacvitiy, click the button to jump to the third activity and then return to get the value passed in the third activity.

(1) When jumping through the Startactivityforresult () method to make a worthwhile callback, the first parameter is the intent object, the second parameter is Requestcode (request code). The Requestcode is used in the callback method after the return.

        Button Gothiredactivitybutton = (Button) Findviewbyid (R.id.go_third_button);        Gothiredactivitybutton.setonclicklistener (new  View.onclicklistener () {            @Override              Public void OnClick (View v) {                // get data from the next activity                new Intent (mainactivity . this, thirdactivity. class );                 1);            }        );

(2) The thing to do in Thirdactivity is to return the value by intent, the specific code is as follows, the return value is also through the intent object Putextra method, then executes the Setreault method. The first parameter of the Setresult () method is the ResultCode (result code), which is also used in callbacks that receive values in the previous activity.

        Button Backbutton = (Button) Findviewbyid (R.id.third_back_button);        Backbutton.setonclicklistener (new  View.onclicklistener () {            @Override            public  void  OnClick (View v) {                = getintent ();                Intent.putextra ("Data_return", "I am the data returned in the third activity");                Setresult (RESULT_OK, intent);                Finish ();            }        });

(3) Then you have to rewrite the callback method that handles the return value in Mainactivity, which is the Onactivityresult callback method. In the method through the key to get passed the value, and assign the value to mainactivity in the TextView specific code is as follows:

1 @Override2     protected voidOnactivityresult (intRequestcode,intResultCode, Intent data) {3         Switch(requestcode) {4              Case1:5                 if(ResultCode = =RESULT_OK) {6String returneddata = Data.getstringextra ("Data_return");7 8TextView Returneddatatextview =(TextView) Findviewbyid (R.id.return_textview);9 Returneddatatextview.settext (returneddata);Ten                 } One                  Break; A         } -}

After the above steps, run the effect as follows, click Go Third activity will jump to thirdactivity, Then clicking the Back button from the thirdactivity will display the value returned in the thirdactivity on the TextView in the previous activity, as shown below.

Today's blog will be here first, the next section of the blog will introduce the life cycle of activity and menu.

The code required in this blog is GitHub share address:https://github.com/lizelu/ActivityCreateAndJumpDemo

Create jump and pass value for Android development activity

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.