How to Bind View with Kotlin Android Extensions Without findViewById?


Introduction

Kotlin Android Extensions are a Kotlin plugin, and that will allow to recover views from Activities, Fragments and Views.

Configuring the Dependency

Enable the Android Extensions Gradle plugin in your module's build.gradle file:

apply plugin: 'kotlin-android-extensions' 

Import all widget properties for a specific layout

(if the layout filename is activity_main.xml):

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

Call the synthetic properties on View

(if the layout filename is activity_main.xml):

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

After that, you can invoke the corresponding extensions, which are properties named after the views in the XML file. For example, for this view:

<TextView
android:id="@+id/tvHelloWorld"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

There will be a property named tvHelloWorld:

//set Text
this.tvHelloWorld.setText("Hello World")

//set Text Size
this.tvHelloWorld.setTextSize(40F)

//set Text Color
this.tvHelloWorld.setTextColor(Color.parseColor("#0000FF"))

Kotlin Android Extensions

Kotlin Android Extensions: Say goodbye to findViewById

張貼留言

0 留言