Kotlin中的按钮数组 [英] Array of buttons in Kotlin

查看:124
本文介绍了Kotlin中的按钮数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Kotlin的android studio中创建按钮数组?我已经在XML文件中创建了带有其ID的按钮,现在我想在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 elements.

我尝试过这样的事情:

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

然后:

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

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

However button names from xml don't work in kotlin file, how can I use them?

推荐答案

假设您具有这样的布局:

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>

首先,使用

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)

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

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

这篇关于Kotlin中的按钮数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆