Use Kotlin to develop an elegant Android app

Source: Internet
Author: User
Tags getcolor

Code portal written in front

In a previous article, we simply know the advantages of the new language Kotlin, but also contact some common grammar and its simple use, I believe you will have a strong interest in it, for the moment to understand that it is interested in it, ha haha. So, how do we apply this new language to Android? Today's article takes you through the development of Android apps using Kotlin, and compares our traditional language Java, so you really feel his beauty and elegance.

Configuration

Project Gradle File

‘com.android.application‘apply plugin:‘kotlin-android‘apply plugin:‘kotlin-android-extensions‘{    classpath ‘org.jetbrains.kotlin:kotlin-gradle-plugin:1.1.1‘}

App Gradle files:

‘org.jetbrains.kotlin:kotlin-stdlib:1.1.1‘‘org.jetbrains.anko:anko-sdk25:0.10.0-beta-1‘// sdk15, sdk19, sdk21, sdk23 are also available‘org.jetbrains.anko:anko-appcompat-v7:0.10.0-beta-1‘
Anko

With the above configuration, you will find the Anko dependencies introduced. Anko is a powerful library developed by JetBrains, speaking of JetBrains, that's great, Kotlin language is their development, the most popular development tools IntelliJ idea are they developed, as is based on idea. Well, anyway, Anko is a kotlin officially developed Kotlin library that lets you develop Android apps faster and simpler, and makes the code we write easier and clearer and easier to read. It consists of several parts, as follows

libraryofforandonandtypetowritedynamicandforonlibrary

So next, we'll use code to understand the advantages of Kotlin language in developing Android.

No more Findviewbyid.

People who have done Android development know that layout files are written much, Findviewbyid is also a lot of work, but also to declare variables, in Findviewbyid and then strong to our control, the use of the following general

TextView username;username=(TextView)findViewById(R.id.user);username.setText("我是一个TextView");

Sometimes the writing is not to vomit, maybe some people say that now is not a few annotated libraries, such as Butterknife, when we use annotations can not Findviewbyid, use the following way

@BindView(R.id.user)TextView username;username.setText("我是一个TextView");

Indeed, the use of annotations does give us a bit less work, but this is still not the most simplistic, and the simplest is that we can directly assign a value to the user-ID control, and you might feel a little bit weird. But Kotlin did do it. We can write this straight.

user.text="我是一个TextView"

See this you have a kind of brief encounter feeling, too tama concise. The user is the id,.text of our layout file statement and we want to give it to SetText (), in Kotlin language, we don't see the Set/get method in Java. It is important to note that when we want to use this (without Findviewbyid, we need to use the XML control in Gradle to join the Apply plugin: ' kotlin-android-extensions '), we need to add the following sentence code

//activity_login就是我们的布局import kotlinx.android.synthetic.main.activity_login.*
Anko Layout

Usually we use XML files to write our layout, but he has some shortcomings such as not type-safe, not empty security, parsing XML files consumes more CPU and power, and so on. and Anko layout can create our UI dynamically using a DSL, and it's much more concise than using Java to dynamically create layouts, and it's a hierarchical relationship with XML-created layouts that makes it easier to read.

verticalLayout {            val textView=textView("我是一个TextView")            val name = editText("EditText")            button("Button") {                onClick { toast("${name.text}!") }            }        }

We can remove the Setcontentview in the OnCreate method, and then add the above code to show the effect, that is, a vertical linear layout, put a textview, a edittext, and a button. And there is a click event in the button that will edittext the content when clicked
Displayed as toast.

The above code is not easy to understand, of course, the default control does not meet our needs, such as we will change the font color and size, will set the width and height, set the margin,padding value, then how to do it, of course, is very simple, Because its logical and XML writing layout is a routine. For example, the following implementations

val textView=textView("我是一个TextView"){                textSize = sp(17).toFloat()                textColor=context.resources.getColor(R.color.red)            }.lparams{                margin=dip(10)                height= dip(40)                width= matchParent            }

I don't think I need to explain the code above, you should see the effect of the control. Because its properties correspond to the name of the property that we set in XML.

In the process of creating the UI above, we directly write the code to create the UI in the OnCreate method, and of course, there is a way to do it. We create an inner class that implements the Ankocomponent interface and overrides the CreateView method, which returns a view, which is the layout we created. Modify the following

Innerclassui:ankocomponent<loginactivity> {Override  FunCreateView (ui:ankocontext<loginactivity>): View {return  with(UI) {verticallayout {ValTextview=textview ("I am a textview.") {textSize = SP ( -). Tofloat () Textcolor=context.resources.getcolor (r.color.red)}.lparams{ Margin=dip (Ten) height= Dip ( +) Width= Matchparent}ValName = EditText ("EditText") button ("button"{onClick {view-) toast ("Hello, ${name.text}!.")                        }                   }               }           }        }    }

Then add a line of code to the OnCreate method to create our layout page. As follows

UI().setContentView(this@LoginActivity)

Now we compile and run and find the same interface as the layout file. But its performance is advantageous, in fact, it does not realize the performance advantage. Anyway, this DSL is really easy to read, but also easy to get started, in the above code, you may notice the DIP (10), which means to convert 10dp to pixel meaning, is anko extension function, said extension function, if read the source of Anko we found a lot of the use of extension functions, This is also one of the advantages of Kotlin language. Really powerful, such as dip extensions (extract view extensions)

fun View.dip(value: Int): Int = context.dip(value)fun Context.dip(value: Int): Int = (value * resources.displayMetrics.density).toInt()

In the above resources.displayMetrics.density and our Java getresources (). Getdisplaymetrics (). Density is an effect, But looking at you will feel more comfortable than the Java writing, anyway I feel so.

In the above we add a click event to the button and we find that it supports lambda expressions. We want to show a toast, just a toast ("content") on it, and it's not that simple. In fact, it is also an extension function that implements

inline fun AnkoContext<*>.toast(message: CharSequence) = ctx.toast(message)fun Context.toast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()

Of course the creation of dialog is still very simple, as follows

            alert ("我是Dialog"){                      yesButton { toast("yes")}                      noButton {  toast("no")}                    }.show()

The more you see the more comfortable, haha. Another powerful and simple, simple and concise piece of code implementation.

        doAsync {            //后台执行代码            uiThread {             //UI线程            toast("线程${Thread.currentThread().name}") }        }

This code implements the Asynctask effect, but you should find that it is more concise than Java implementation, unless it is color-blind, otherwise you will see concise.

If you use Kotlin to develop Android for a period of time, you will find that it gives us a lot less code, of course, more advantages and usage we need to explore. I believe it will surprise you after exploration.

Implementation of a simple login interface

The interface is simple, pseudo-code

<linearlayout><ImageView/><linearlayout> <ImageView/><edittext account /><linearlayout><linearlayout> <ImageView/><edittext password /><linearlayout><Button login/><linearlayout> <CheckBox remember password/><TextView Privacy Agreement Xieu/><linearlayout><TextView/></linearlayout>

Look not complicated, then the XML implementation of the code is not posted here, if you want to see the XML implementation can be viewed, then the next step is to see Anko in the Kotlin code to implement this layout.

lateinit var et_account:edittext lateinit var et_password:edittext inner class Loginui:ankocomponent<loginact                ivity> {override CreateView (ui:ankocontext<loginactivity>) = with (UI) {verticallayout { BackgroundColor = Context. Resources. GetColor(Android. R. Color. White) Gravity = Gravity. CENTER_horizontal ImageView (R. Mipmap. IC_launcher). Lparams{width = Dip ( -) Height = Dip ( -) TopMargin = Dip ( -)} linearlayout {gravity = Gravity. CENTER_vertical Orientation = Horizontal Backgroundresource = R. drawable. BG_frame_corner ImageView {image = Resources. Getdrawable(R. Mipmap. IC_username)}. Lparams(width = wrapcontent, height = wrapcontent) {LeftMargin = Dip ( A) RightMargin = Dip ( the)} Et_account = editText {hint ="Login Account"Hinttextcolor = Color. Parsecolor("#666666") TextSize = -F background = null}}. Lparams(Width = Dip ( -), height = Dip ( +) {TopMargin = Dip ( $)} linearlayout {orientation = horizontal background Resource = R. drawable. BG_frame_corner Gravity = Gravity. CENTER_vertical ImageView {image = Resources. Getdrawable(R. Mipmap. IC_password)}. Lparams{LeftMargin = Dip ( A) RightMargin = Dip ( the)} Et_password = editText {hint ="Login Password"Hinttextcolor = Color. Parsecolor("#666666") TextSize = -F background = null}}. Lparams{width = Dip ( -) Height = Dip ( +) TopMargin = Dip (Ten)} button ("Login") {gravity = Gravity. CENTERBackground = Resources. Getdrawable(R. drawable. BG_LOGIN_BTN) TextColor = Color. Parsecolor("#ffffff") OnClick {if (et_account. Text. toString(). Isnotempty() && Et_password. Text. toString(). Isnotempty()) startactivity<mainactivity> () Else toast ("Please enter your account or password")                    }                }. Lparams(Width = Dip ( -), height = Dip ( -) {TopMargin = Dip ( -)} linearlayout {orientation = horizontal Gravity = Gravity. CENTER_vertical CheckBox ("Remember Password") {TextColor = Color. Parsecolor("#666666") TextSize = -F leftpadding = Dip (5)} TextView ("Privacy Agreement") {TextColor = Color. Parsecolor("#1783e3") Gravity = Gravity. RightTextSize = -F}. Lparams(width = matchparent)}. Lparams(Width = Dip ( -) {TopMargin = Dip ( -)} TextView ("Copyright?" Code4android ") {textSize = -F gravity = Gravity. CENTER orGravity. BOTTOM}. Lparams{bottommargin = Dip ( *) Weight =1F}}}}

See the code above, it looks good, even if you do not write now, but you can read it. In the above we set the login button to an event that opens mainactivity. StartActivity's <> writes about the activity we're going to jump to, and if we pass parameters to the open interface, it's written directly in (). For example, we will enter the account number and password to the jump interface, then implemented as

startActivity<MainActivity>("account"to et_account.text.toString(),"password"to et_password.text.toString())

In fact, the strength of Anko far more than this, it is worth our careful taste. Want more in-depth study can go to GitHub Anko, to this, this article also ended, if in reading found the mistake, welcome to point out, thank you, has a wonderful day.

Use Kotlin to develop an elegant Android app

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.