android - 使用 kotlin 在 android studio 中创建按钮

标签 android button kotlin android-studio-3.0

这是我在activity_main.xml 中的按钮

    <Button
        android:text="@string/fs"
        android:layout_width="154dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/textView" 
        android:layout_marginEnd="12dp"
        android:layout_marginRight="12dp" 
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" 
        android:layout_marginLeft="16dp"
        android:layout_marginStart="16dp" android:layout_marginBottom="32dp"
        app:layout_constraintBottom_toTopOf="@+id/imageView" 
        app:layout_constraintHorizontal_bias="0.451"
        app:layout_constraintVertical_bias="0.069" android:id="@+id/button2"
        style="@style/Widget.AppCompat.Button" 
        android:background="@android:color/holo_green_dark"
        android:onClick="flowerpage"/>

这是我相信 Mainactivity.kt 中正在创建的按钮

fun flowerpage(view: activity2) {
}

我是 Kotlin 的新手,但是,我习惯使用 HTML,您可以通过 HTML 链接将两个网页连接在一起,但是,这似乎并不那么简单。

    button2.setOnClickListener {flower_button()}

这显示编译器错误。我错过了导入吗??

最佳答案

使用 kotlin,您只需在 XML 中为按钮提供一个 id,然后就可以执行以下操作:

btn_id_you_gave.setOnClickListener {doSomething()}

private fun doSomething() {...}

您无需在 XML 中执行 OnClick 操作即可充分利用 Kotlin。

关于android - 使用 kotlin 在 android studio 中创建按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53807677/

相关文章:

Android深度链接问题

android - WebView 显示 ERR_CLEARTEXT_NOT_PERMITTED 尽管站点是 HTTPS

安卓在后台播放音乐

java - Android 的菜单问题

css - 使社交媒体按钮(Facebook、Twitter 等)响应

android - 如何检查 SwitchPreference 的当前状态?

kotlin - 在Kotlin/TornadoFX中关闭 View 后如何执行清理操作?

Android - 使用静态布局在位图底部绘制文本

c++ - 处理不同的图形用户界面状态

kotlin - TornadoFX TableView:获取选定的行值