Kotlin 綁定Android控件

佈局文件:activity_test_kt.xmljava

<?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, findViewByIdandroid

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")
        }
    }
複製代碼

結果: bash

方式二

app下的 build.gradle 中添加app

apply plugin: 'kotlin-android-extensions'
複製代碼

基本上Android Studio 會默認添加ide

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,直接使用對應控件gradle

結果ui

相關文章
相關標籤/搜索