首页 > 解决方案 > Kotlin 中的按钮数组

问题描述

如何在 Kotlin 的 android studio 中创建按钮数组?我在 xml 文件中创建了带有 id 的按钮,现在我想在 Kotlin 代码中使用与数组元素相同的按钮。

我试过这样的事情:

var buttons: Array<Button> = Array(25)

接着:

buttons[0] = btn1 // btn1 as the id from xml file

但是 xml 中的按钮名称在 kotlin 文件中不起作用,我该如何使用它们?

标签: androidarraysbuttonkotlin

解决方案


假设你有这样的布局:

<?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>

build.gradle首先,在你的with中应用 kotlin 扩展插件来合成语法

apply plugin: 'kotlin-android-extensions'

然后,您可以通过执行以下操作简单地初始化代码中的按钮数组:

val buttons = arrayOf(btOne, btTwo, btThree)

否则,如果您不想使用 kotlin syntetic,只需使用旧的 findviewbyid 语法

val buttons = arrayOf(
            findViewById(R.id.btOne),
            findViewById(R.id.btTwo),
            findViewById<Button>(R.id.btThree)
        )

推荐阅读