Array of buttons in Kotlin

半城伤御伤魂 提交于 2021-02-10 05:26:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!