Developing Android Apps with Kotlin (IV): Custom views and Android extensions

Source: Internet
Author: User

Developing Android Apps with Kotlin (IV): Custom views and Android extensions

@author ASCE1885 's Github book Weibo CSDN
Original link

After reading the extension function and the default value of this article, then what to introduce next? As we said in the first article in this series, Kotlin makes Android easier to develop, and we'll cover it further in this article.

Custom View

As you recall, when it comes to the limitations of Kotlin, we mention that custom views are not supported in earlier versions of Kotlin (M10), because only one constructor can be created for each class at that time. This is usually enough, because with optional parameters, we can create enough variants of the constructor, for example:

class MyClass(param: Int, optParam1: String = "", optParam2: Int = 1) {??    init {?        // Initialization code?    }?}

With this constructor, we have the following four ways of creating this class:

val myClass1 = MyClass(1)val myClass2 = MyClass(1"hello")val14)val myClass4 = MyClass(1"hello"4)

As you can see, we get a bunch of combinations using optional parameters. However, we may encounter problems when creating custom views by inheriting common views. Custom views need to rewrite one or more constructors to work properly, but we can't do that. Fortunately, the automatic Kotlin M11 begins, and we can declare multiple constructors, similar to Java. The following is a square ImageView:

classSquareimageview:imageview{public Constructor (Context:context): Super (context) {}     Public  Constructor(Context:context, Attrs:attributeset) :Super (context, attrs){    }     Public  Constructor(Context:context, Attrs:attributeset, Defstyleattr:int) :Super (context, attrs, defstyleattr){    }    OverrideFun Onmeasure (Widthmeasurespec:int, Heightmeasurespec:int){super.onmeasure (Widthmeasurespec, heightmeasurespec) val width = getmeasuredwidth () setmeasure Ddimension (width, width)}}

With a very simple code we implemented a custom views.

Kotlin Android Extensions

The addition of extensions from Kotlin M11 makes it easier for Android developers to get views defined in the XML file. You might think it's a lot like butterknife, but it's easier to use.

The Kotlin android extension is essentially a view binding that allows developers to use the views defined in the XML file through the ID in the code. it will automatically create attribute values for views without using a third-party annotation framework or the Findviewbyid function.

To use this feature, you first need to install the plugin "Kotlin Android Extension" and add a new classpath in the build script dependency of the Build.gradle file:

buildscript {?    …?    dependencies {        …?        "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"    }?}

If you define a layout file named Main.xml:

<framelayout?    xmlns:android="..."?    android:id="@+id/framelayout"?    android:orientation="vertical"?    android:layout_width="Match_parent"? android:layout_height="Match_parent">    ??<TextView?        android:id="@+id/welcometext"?        android:layout_width="Wrap_content"? android:layout_height="wrap_content"/>        ??</framelayout>

If you want to use the views defined in this file in the activity, you only need to import the synthetic attribute value of the XML file as follows:

import kotlinx.android.synthetic.<xml_name>.*

Specifically to our example, it looks like this:

import kotlinx.android.synthetic.main.*

This allows you to use the ID to obtain references to these views:

override fun onCreate(savedInstanceState: Bundle?) {?    super<BaseActivity>.onCreate(savedInstanceState)    setContentView(R.id.main)?    frameLayout.setVisibility(View.VISIBLE)?    welcomeText.setText("I′m a welcome text!!")?}
Summarize

The introduction of these two new features gives us a glimpse of the Kotlin team's commitment to making Android easier to develop. They also released a library of functions called Anko, a domain-specific language (DSL) that creates an Android layout from a Kotlin file. I haven't used its main features yet, but when it comes to working with Android views, you can use it to simplify your code. There are also examples of open source projects I uploaded to GitHub, Bandhook-kotlin.

The next article describes the use of lambda expressions and how it simplifies the characteristics of code and extended languages. A very interesting feature, in my opinion, this is the most powerful aspect of Kotlin compared to Java 1.7.

Appreciation of photography at the end of Wen

Developing Android Apps with Kotlin (IV): Custom views and Android extensions

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.