首页 > 解决方案 > 如何在 Android Kotlin 中使用 onclicklistner 获取按钮文本?

问题描述

我是Android的初学者。我正在制作一个笑话 api 应用程序,每个按钮都是类别。所以我需要获取按钮的文本内容。这是我的 xml 代码。我看了很多线程,但都在java中

 <Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@id/button2"
    android:layout_marginTop="20dp"
    android:text="science"
    android:onClick="getJoke"
    />

标签: androidkotlin

解决方案


fun getJoke(v:View) {
  val b = v as Button
  val buttonText = b.getText().toString()
}

推荐阅读