Array Of Buttons In Kotlin
How can I create array of buttons in android studio in Kotlin? I've created buttons with their ids in a xml file, now I want to use the same buttons in my Kotlin code as array's el
Solution 1:
Supposed you have a layout like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
android:orientation="vertical">
<Button android:id="@+id/btOne" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="one"/>
<Button android:id="@+id/btTwo" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="two"/>
<Button android:id="@+id/btThree" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="three"/>
</LinearLayout>
First, apply kotlin extensions plugin for syntetic syntax in your build.gradle
with
apply plugin: 'kotlin-android-extensions'
Then, you can simply initalize an array of buttons in your code by doing:
val buttons = arrayOf(btOne, btTwo, btThree)
Otherwise, if you don't want to use kotlin syntetic, simply use the old findviewbyid syntax
val buttons = arrayOf(
findViewById(R.id.btOne),
findViewById(R.id.btTwo),
findViewById<Button>(R.id.btThree)
)
Post a Comment for "Array Of Buttons In Kotlin"