Kotlin Getting Started (21) Jump processing on the active page

Source: Internet
Author: User

Activity page Jump is one of the most commonly used features of the app, in the previous chapters of the demo source has been seen many times, often click on a button on the interface, and then jump to the corresponding next page. For app developers, the implementation of this feature is very common, using Java encoding but the following two lines of code:

    Intent Intent = new Intent (mainactivity.this, linearlayoutactivity.class);    StartActivity (Intent);

The key to the above code is the intent constructor, where the first parameter specifies the source of the page jump action, that is, the source page of the mainactivity, Mainactivity.this is usually abbreviated as this; the second parameter of the construction intent represents the destination of the page jump action, that is, the target page of linearlayoutactivity. If you convert these two lines of Java code to Kotlin code (copy the two lines and paste into the kt file, Android Studio will automatically complete the conversion), you can see the Kotlin code for the active jump as follows:

    Val Intent = Intent ([email protected], Linearlayoutactivity::class.java)    startactivity (Intent)

In contrast, the Kotlin code here differs from the Java code in two main points:
1, within the class refers to its own this keyword, Java's complete wording is "class name. This", and Kotlin's full wording is "[email protected] class name", of course, both can be abbreviated as "this";
2, to get a class object, Java is written as "class name. Class", and Kotlin's writing is "Class Name:: Class.java", a look will know with thick Java flavor;
It seems that the Kotlin code and Java code Dora, without obvious simplification, makes a small disappointment. But the attentive reader may have noticed, the book appendix Source of activity jumps, not the above Kotlin authentic wording, but the following this simplified version of the wording:

    Startactivity<linearlayoutactivity> ()

The reason is that the Anko library uses the extension function of Kotlin to add a new method named StartActivity to the context class. Therefore, before using the simplified version of the notation, you must first import the Anko library's specified file, that is, the KT file header add the following line import statement:

Import org.jetbrains.anko.startActivity

When the activity page jumps, often also carries some request parameter, if uses the Java code, can easily call the intent object's PutExtra method, passes the message through "PutExtra (parameter name, parameter value)" Way, just like the following code:

    Intent Intent = new Intent (this, actsecondactivity.class);    Intent.putextra ("Request_time", Dateutil.getnowtime ());    Intent.putextra ("Request_content", Et_request.gettext (). toString ());    StartActivity (Intent);

It is also easy to use Anko's simplified notation, as long as the field names and field values of each parameter fields are filled in parentheses after startactivity, the specific Kotlin jump code is as follows:

    In the first notation, the parameter names and parameter values are separated by the keyword to    startactivity<actsecondactivity> (            "Request_time" to Dateutil.nowtime,            "Request_content" to Et_request.text.toString ())

Notice that the above notation uses the keyword to separate parameter names and parameter values, feeling not beautiful enough, and easily confusing, to follow the field name or field value? So the Anko library provides another way of conforming to the custom, that is, using the pair class to pair the parameter name and the argument value, the first parameter of the pair is the field name, and the second parameter is the field value. The Kotlin jump code that is rewritten accordingly is as follows:

    The second way, using the pair to match the parameter name and the value of the    startactivity<actsecondactivity> (            "Request_time", Dateutil.nowtime),            Pair ("Request_content", Et_request.text.toString ()))

In either case, the same way that the request parameters are parsed in the next activity is to get the bundle object first, and then get the corresponding field value based on the field name, respectively. The specific request parameter resolution code is as follows:

Class Actsecondactivity:appcompatactivity () {    override fun OnCreate (Savedinstancestate:bundle?) {        super.oncreate (savedinstancestate)        Setcontentview (R.layout.activity_act_second)        val bundle = Intent.extras        val request_time = bundle.getstring ("Request_time")        val request_content = bundle.getstring (" Request_content ")        Tv_response.text =" received request message: \ n Request time is ${request_time}\n request content is ${request_content} "}    

Below the test interface to observe the message before and after the transmission of data sent to the image, as shown in the left, then the first page is ready to jump to the second page, as shown in the right image, this is the second page after the jump, the interface shows the first page passed over the parameter information.

The type of arguments passed between the activity, in addition to the basic data types such as Integer, floating-point, and string, also allows the serialization structure, such as the Parcelable object, to be passed. This Parcelable object is not a simple entity class, but an entity class that implements the Parcelable interface, which means that the class must rewrite all the methods of the interface definition, whether you want to be honest tiger. For example, the previous activity jump passed two field data, if you put these two fields into the Parcelable object, the Parcelable class containing only two fields corresponding Java code is as verbose as follows:

public class Messageinfo implements parcelable {public String content;    Public String Send_time;        Write Data @Override public void Writetoparcel (Parcel out, int flags) {out.writestring (content);    Out.writestring (Send_time); }//Routine implementation createfromparcel and NewArray public static final parcelable.creator<messageinfo> Creator =            New Parcelable.creator<messageinfo> () {//Read data public messageinfo Createfromparcel (Parcel in) {            Messageinfo info = new Messageinfo ();            Info.content = In.readstring ();            Info.send_time = In.readstring ();        return info;        } public messageinfo[] NewArray (int size) {return new messageinfo[size];    }    };    @Override public int describecontents () {return 0; }}

Look at this posture, such a simple custom parcelable class, you have to rewrite including Writetoparcel, Createfromparcel, NewArray, describecontents, including four methods, can be described as selectmen. This shows here is a Java pain point, is suitable for kotlin cast fists, good improvement. In the fifth chapter of the class and object, introduced the Kotlin to the data class writing, in the class name before the keyword Data,kotlin can automatically provide Get/set, equals, copy, ToString and many other methods. Then the transformation of the serialized object is quite simple, just add a line of annotations before the class name "@Parcelize", the Kotlin code for the entire class is only a few lines below:

@Parcelizedata class Messageinfo (Val content:string, Val send_time:string): parcelable {}

However, if you want to compile properly, you also need to modify the module's compiled file Build.gradle, add the following lines at the end of the file, to increase the build support for Android plugins:

@Parcelize tag needs to be set experimental = trueandroidextensions {    experimental = true}

After the compilation file has been modified, the annotations of the serialized object can now be used in the Kotlin. Although there is no line of code inside the custom Messageinfo class, it automatically implements several methods of the Parcelable interface in addition to all the methods of the data class. Next you can use this class to transfer the serialized data of the activity jump, the following is the rewritten Kotlin jump code:

    Val request = Messageinfo (Et_request.text.toString (), dateutil.nowtime)    startactivity< Parcelablesecondactivity> ("message" to request)

After jumping the next page, call Getparcelable to get the original serialized data, the specific data parsing code is as follows:

Class Parcelablesecondactivity:appcompatactivity () {    override fun OnCreate (Savedinstancestate:bundle?) {        super.oncreate (savedinstancestate)        Setcontentview (R.layout.activity_parcelable_second)        Val Request = intent.extras.getparcelable<messageinfo> ("message")        Tv_response.text = "received packaged request message: \ n Request time is ${ request.send_time}\n request content is ${request.content} "}    }

Also through the test interface to observe the serialized object packaging and unpacking effect, as shown in the left image, then the first page is ready to jump to the second page, as shown in the right image, this is the second page after the jump, the interface shows the first page passed over the serialized data.

Kotlin Getting Started (21) Jump processing on the active page

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.