问题
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 elements.
I've tried something like this:
var buttons: Array<Button> = Array(25)
and then:
buttons[0] = btn1 // btn1 as the id from xml file
However button names from xml don't work in kotlin file, how can I use them?
回答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)
)
来源:https://stackoverflow.com/questions/55301944/array-of-buttons-in-kotlin