使用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

 


免責聲明!

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



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