kotlin-----代替findViewById的方法


在安卓項目使用了Kotlin之后,發現Kotlin一個相當強大的地方,可以不用findViewById,引入布局,直接使用控件,使用kotlin插件自動生成

 

1、在 application.gradle 中引入kotlin擴展插件

classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"

 

2、在app.gradle中應用擴展插件

apply plugin: 'kotlin-android-extensions'

 

3、使用、引入kotlin自動生成的相關布局文件

import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button_Test.setOnClickListener{
            textTest.text = "onClick賦值成功!"
        }
    }
}

 

布局代碼:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.mvp.org.MainActivity">

    <com.beardedhen.androidbootstrap.BootstrapWell
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="8dp"
        app:bootstrapSize="sm">

        <TextView
            android:id="@+id/textTest"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Look, I'm in a large well!"
            />
    </com.beardedhen.androidbootstrap.BootstrapWell>

    <com.beardedhen.androidbootstrap.BootstrapButton
        android:id="@+id/button_Test"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="測試按鈕"
        app:bootstrapBrand="warning"
        app:bootstrapSize="lg"
        app:buttonMode="regular"
        app:showOutline="false"
        app:roundedCorners="true"
        />

</LinearLayout>

運行結果:

運行后:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM