1. 程式人生 > >Kotlin for Android (IV): Custom Views and Android Extensions

Kotlin for Android (IV): Custom Views and Android Extensions

After reading what can do for you, you might be wondering what´s next. As we talked in , this language makes Android development much simpler and there are still some more things I´d like to talk about.

Custom Views

Kotlin, by default, only uses one constructor per class. This is usually enough, because using we can create as many variations of the constructor as we may need. Here it is an example:

class MyClass(param: Int, optParam1: String = "", optParam2: Int = 1) 
{


    init {

        // Initialization code

    }

}

With a unique constructor, we now have four ways to create this class:

val myClass1 = MyClass(1)
val myClass2 = MyClass(1, "hello")
val myClass3 = MyClass(param = 1, optParam2 = 4)
val myClass4 = MyClass(1, "hello", 4)

As you see, we get a whole bunch of combinations just by using optional parameters. But this leads to a problem if we are trying to create an Android custom view by extending one of the regular views. Custom views need to override more than one constructor to work properly. Luckily, we have a way to declare more constructors in way similar to what we do in Java. This is an example of an ImageView

which preservers a squared ratio:

class SquareImageView : ImageView {

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = getMeasuredWidth()
        setMeasuredDimension(width, width)
    }
}

Quite simple. It could probably be less verbose, but at least we have a way to do it.

Kotlin Android Extensions

If you didn’t know about Kotlin Android Extensions, you’re gonna love them. They will help us Android developers to access to the views declared in an XML in a much easier way. Some of you will remember Butterknife when you see it, but it´s even simpler to use.

Kotlin Android Extensions is basically a view binder that will let you use your XML views in your code by just using their id. It will automatically create properties for them without using any external annotation or findViewById methods.

To start using it, you´ll need to include the new plugin into the build.gradle:

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions

...

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}

Imagine you have declared the next layout, called activity_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 these views in your activity, the only thing you need to do is importing the synthetic properties for that xml:

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

In our case, it will be just activity_main:

import kotlinx.android.synthetic.main.activity_main.*

Now you can access your views by using its id:

override fun onCreate(savedInstanceState: Bundle?) {

    super<BaseActivity>.onCreate(savedInstanceState)
    setContentView(R.id.main)

    frameLayout.setVisibility(View.VISIBLE)

    welcomeText.setText("I´m a welcome text!!")

}

Conclusion

What it´s really promising about these two features is that it´s clear that the Kotlin team is very interested in making Android developers lives easier. They also released a library called Anko, a DSL to create Android layouts from Kotlin files. I´m not using its main functionality yet, but you can use it to simplify your code when dealing with Android views, and I have some examples of this in the . You can take a look to see this and many other things.

Next article will cover the use of lambda expressions and how they can help us simplify our code and extend the language. Really interesting one! To me, the most powerful aspect of Kotlin when compared with Java 1.7.

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares

Like this:

Like Loading...

相關推薦

Kotlin for Android (IV): Custom Views and Android Extensions

After reading what can do for you, you might be wondering what´s next. As we talked in , this language makes Android development much simpler and th

Custom Views in Android with Kotlin (KAD 06)

When we saw the article about classes, you may remember that in general only one constructor is used. This is a problem for creating custom views. Th

Some Thoughts on Android's new ConstraintLayout and Android Studio's new Design Editor

At this year's IO Google introduced a new layout - the ConstraintLayout - and also presented it's totally revamped la

Kotlin for Android (III): Extension functions and default values

Now that you know the basics about Kotlin and how to configure your project, it´s time to talk about some interesting things that Kotlin can do for u

Who is Open Source? Android O Preview 3. Kotlin for Android. And Vaadin 8!

GitHub Survey: Open Source is Raining Men! A 2017 GitHub survey of 5500 randomly selected participants, most of whom work on GitHub.com open source pro

更新 是 可用的 針對 安卓 軟件開發包和工具 Updates are available for android software development packages and tools

安卓 模擬器 軟件 ide software ava -m android 設置 作者:韓夢飛沙 Author:han_meng_fei_sha 郵箱:[email protected]/* */ E-mail: 313134555 @qq.com

快速切換至Kotlin for Android模式

前言 關於Kotlin的文章,已經構思了很久。一直不知道該怎麼寫。文件式文章?那不如直接看文件,何必需要我再多“嗶嗶”呢。思來想後,決定寫一篇快速在Android開發中感受Kotlin的其妙的文章。 說實話,最開始搞Kotlin我是拒絕的。為啥?因為完全沒有感覺到用它替換Java開發有什麼實質性的改變;而

極簡Kotlin-For-Android(一)

安裝 Kotlin 外掛 Android Studio 3.+ 已經有了 Kotlin 外掛,如果是更早的版本,點選 Android Studio | File | Settings | Plugins,搜尋 Kotlin ,安裝,重啟 Android Studio . 建立工程 點選 Android

Conflict with dependency 'com.android.support:support-annotations' in project ':xxx'. Resolved versions for app (25.4.0) and test app

Conflict with dependency 'com.android.support:support-annotations' in project ':xxx'. Resolved versions for app (25.4.0) and test app (27.1.1) differ 問題解決

極簡Kotlin-For-Android(二)

上一篇我們做到了從網路獲取資料,並寫好了實體類.接著我們需要建立domain層,這一層為app執行任務. 構建domain層 首先需要建立command: public interface Command<T> { fun execute() : T } 複製程式碼 建立DataMap

Show HN: Voice Overlay for iOS and Android Apps

We're seeing at Algolia a lot of developers implementing speech to text in their mobile apps, but didn't see much in the way of tooling to help them do it.

We built our iOS and Android apps in Java & Kotlin

We built our iOS and Android apps in Java & Kotlin — one year laterMonday morning, first cappuccino, first lines of a new feature we’re adding to our m

Top 5 IntelliJ IDEA and Android Studio Courses for Java and Android Development

There is no doubt that IntelliJ IDEA is THE best IDE for Java development, even though Eclipse may still be probably used by more people because it's FREE

Blog-08-《一週快速上手Kotlin For Android》-之ArrayList

在 Kotlin 中沒有實現和 Java 一樣的 List 集合,而是使用了和 Java 一樣的 ArrayList 集合。Kotlin 中提供了以下四種函式方法來使用 ArrayList,分別是 1、listOf()2、listOfNotNull()3、mutableListOf()4、arraylistO

Blog-06-《一週快速上手Kotlin For Android》-之When分支

—《一週快速上手Kotlin For Android》簡介目前Kotlin已正式成為Android的官方語言,作為Android開發者來說,學習和了解Kotlin也是屬於理所當然的事情,興許你覺得Jav

Blog-04-《一週快速上手Kotlin For Android》-之Activity詳細用法

—《一週快速上手Kotlin For Android》簡介 目前Kotlin已正式成為Android的官方語言,作為Android開發者來說,學習和了解Kotlin也是屬於理所當然的事情,興許你覺得Java對於你來說才是真正的開發”利器”,使用Java你能發揮

Kotlin for Android

在Google IO 2017 大會上,Google將 Kotlin列為 Android官方開發語言,Android Studio 3.0 也預設集成了Kotlin外掛。 如果您是更早的版本,點選Android Studio File->Settin

Blog-07-《一週快速上手Kotlin For Android》-之陣列

—《一週快速上手Kotlin For Android》簡介目前Kotlin已正式成為Android的官方語言,作為Android開發者來說,學習和了解Kotlin也是屬於理所當然的事情,興許你覺得Java對於你來說才是真正的開發”利器”,使用Java你能發揮更高的效率,當然,如果如此你還是可以繼續使用Java

Kotlin for Android(九)Kotlin集合

一、結構 集合在我們實際開發中用的還是比較頻繁的,Kotlin中的集合不同於Java中的集合, Kotlin中的集合根據“是否可變”,分為兩派:可變集合與不可變集合(可變集合可以在初始化後add新資料,不可變集合只能get資料,不能add資料),而後者是 在前

一步步學習kotlin for android(三) kotlin省略findviewById

findViewById      今天的內容涉及到findViewByID,android語言原來這個特別繁瑣,現在好了,kotlin語言,直接拿來佈局裡面的id用,省去好多重複工作量啊 在使用kotlin的id之前,需要先在builde.gradle裡引入這個 app