Kotlin Android Extensions is an important Kotlin plugin that is similar to Butterknife. It will allow to recover views in android.
Implementation
apply plugin:'com.android.application'
apply plugin:'kotlin-android'
apply plugin:'kotlin-android-extensions'
Coding Part
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context="com.androidmads.kotlinsample_helloworld.MainActivity">
<TextView
android:id="@+id/helloTxtView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<TextView
android:id="@+id/helloAndroidExtension"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Hello World!" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
app:srcCompat="@mipmap/ic_launcher" />
</LinearLayout>
import kotlinx.android.synthetic.main.activity_main.*;
The following code refers that how to use Kotlin Extension. Here helloAndroidExtension is the Id of the textview and click listener for this textview is done as in below code
// Hello Program for Kotlin Android Extension
// helloAndroidExtension is the id of the TextView
helloAndroidExtension.text = "Example for Kotlin Android Extension";
We can apply the same Approach with imageview by assigning ImageSource from Drawable folder and see the code below.
imageView.setImageResource(R.mipmap.ic_launcher_round)
Full Code
The following shows, how to use Kotlin Android extensionspackage com.androidmads.kotlinsample_helloworld
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*;
class MainActivity : AppCompatActivity() {
// Declaration
var helloTextView: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initialization
helloTextView = findViewById(R.id.helloTxtView) as TextView
// Assigning data to TextView in runtime
helloTextView!!.text = "Hello Kotlin!";
// Click Listener in Kotlin
helloTextView!!.setOnClickListener({
Toast.makeText(applicationContext, "Hello TextView Clicked",
Toast.LENGTH_LONG).show();
})
// Hello Program for Kotlin Android Extension
helloAndroidExtension.text = "Example for Kotlin Android Extension";
imageView.setImageResource(R.mipmap.ic_launcher_round)
}
}

I think Kotlin is going to take over android Community very very soon
ReplyDeleteLearn Kotlin android
D602AB4952
ReplyDeletetiktok takipçi
swivel glider accent chair