You can access views without findViewById
by using the kotlin-android-extensions
plugin and the LayoutContainer
interface.
In your build.gradle
file make sure that you apply the plugin and set the experimental flag:
apply plugin: 'kotlin-android-extensions'
androidExtensions {
experimental = true
}
The class from which you want to access the list_view
needs to implement the LayoutContainer
interface. Implementing that interface means that you need to provide a container view in which your ListView
can be found.
Now let's assume we have a simple layout that we use for the MainActivity
:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
In our MainActivity
we use this file with setContentView
.
Now you can write a class that is not an activity but is able to use a view (the TextView
in this example) without using findViewById
:
package com.example.playground
import android.view.View
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.activity_main.*
class Demo(override val containerView: View?) : LayoutContainer {
fun setTextViewText(text: String) {
text_view.text = text
}
}
The class implements LayoutContainer
(this is only possible if you first enable the experimental features) and therefore needs to provide the containerView
property which it gets via the constructor.
Now to use this class e.g. from an activity you will need to instantiate it and give it the view in which text_view
exists (the LinearLayout
with the id container
in my case):
val demo = Demo(container)
demo.setTextViewText("Magic!")
You will not be able to use kotlinx.android.synthetic
-magic without providing a container. Because essentially what happens in the background is that if you access list_view
the extension does a findViewById
.
Online you can find additional information from Kotlin about the Android plugin and about how to use the Android extensions.