在安卓项目使用了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>
运行结果:
运行后: