使用Kotlin,抛弃findViewById

有没有觉得Android的findViewById挺烦人的。使用Kotlin可以让你彻底抛弃这个烦恼


步骤1、在build.gradle(Module:app)中添加如下一句话

这个在老一点版本的Android Studio中需要手动添加,我的是Android Studio3.0的,这句话是默认加上的

 1 apply plugin: 'kotlin-android-extensions' 


步骤2、在xml布局文件中添加控件,如下:

1     <TextView
2         android:id="@+id/lab_test"
3         android:layout_width="wrap_content"
4         android:layout_height="wrap_content"
5         android:text="这是切换前的" />

步骤3、在Activity文件中导入:

如果是自动导包的请忽略

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


步骤4,直接使用id即可

1     override fun onCreate(savedInstanceState: Bundle?) {
2         super.onCreate(savedInstanceState)
3         setContentView(R.layout.activity_main)
4 
5         lab_test.setText("这是切换后的")
6         if (lab_test is TextView) {
7             Log.e(TAG, "lab_test is TextView")
8         }
9     }

是不是很方便,是不是有一种很惊艳的感觉!!!!


转载请注明原文地址:http://www.cnblogs.com/yanyojun/p/8013099.html

本文代码已经上传至Github:https://github.com/YanYoJun/DangerousPermission

原文地址:https://www.cnblogs.com/yanyojun/p/8013099.html