android - Kotlin 中的按钮数组

标签 android arrays button 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 文件中不起作用,我该如何使用它们?

最佳答案

假设你有这样的布局:

<?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 中应用 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)
        )

关于android - Kotlin 中的按钮数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55301944/

相关文章:

arrays - Swift 2 Object Mapper 类追加不起作用,结果为零

ruby-on-rails - 如何在 Ruby on Rails 中单击按钮更改值

android - 替换 ImageButton 上的图像

java - 使用 Java 的适用于 Android 的 SendGrid API

arrays - 从 cloudkit-query 获取结果

java - Android 日期格式帮助

ios - 将日期字符串插入有序日期字符串数组中正确的索引处

ios - 保存按钮状态

java - 如何使在主线程中运行的某个类同时等待其他类达到某种特定状态?

Android:使用 acra (couchDB) 向服务器发送错误报告