Kotlin 绑定Android控件

2019-02-15  本文已影响0人  炫子_260f

布局文件:activity_test_kt.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kotlin.test.TestActivityKt">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button1"/>

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button2"/>
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

方式一

类似java, findViewById

    lateinit var button1 : Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test_kt)
        supportActionBar?.setTitle("kt 测试")

        button1 = findViewById(R.id.button1)
        button1.setOnClickListener(){
            Log.d(TAG, "button 1 press")
        }
    }

结果:


image

方式二

app下的 build.gradle 中添加

apply plugin: 'kotlin-android-extensions'

基本上Android Studio 会默认添加

Activity中 import

import kotlinx.android.synthetic.main.activity_test_kt.*

onCreate代码

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test_kt)
        supportActionBar?.setTitle("kt 测试")

        button2.setOnClickListener(){
            Log.d(TAG, "button 2 press")
        }
    }

可以直接通过控件的id,直接使用对应控件

结果

image
上一篇 下一篇

猜你喜欢

热点阅读