相信大家用AS寫頁面的時候,最煩的就是findViewById,尤其是複雜佈局,那感覺太酸爽😂,下面的3中方法我在項目中都在使用,目前感覺良好😄,廢話不多說,文章正式開始~
文章目錄
方案一:使用Android Studio 3.6新特性(附demo)
3.6版本的AS可以進行View Binding,View Binding後可以通過佈局的xml文件生成綁定類來實現與view交互,先用起來:
1.AS在3.6.0及以上
2.build gradle在3.6.0及以上
classpath 'com.android.tools.build:gradle:3.6.0'
3.在每一個使用View Binding的module中配置
android {
...//注意配置在android下
viewBinding {
enabled = true;
}
}
4.比如佈局文件的名字是activity_test_binding.xml,在Activity中使用的時候,先獲取xml文件生成的綁定類,這裏我的佈局文件是activity_test_binding.xml,所以用
ActivityTestBindingBinding mBinding = ActivityTestBindingBinding.inflate(getLayoutInflater());
setContentView(mBinding.getRoot());
此時可以用mBinding 來獲取佈局中所有含有id視圖的直接引用,可以直接通過mBinding.View的ID 來得到View對象,見下圖
佈局activity_test_binding.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".ui.activity.TestBindingActivity">
<Button
android:text="測試view binding"
android:id="@+id/btn_test_view_binding"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="match_parent"
android:layout_height="50dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
在adapter和Fragment中使用時可以調用
佈局名字Binding.bind(View)方法來獲取綁定類。就不過多介紹了
想來個demo運行一下?點我!!!
方案二:使用Kotlin爲Android提供的擴展插件kotlin-android-extensions
1.在module的build.gradle下配置插件
apply plugin: 'kotlin-android-extensions'
...
android{
...
//ViewHolder中使用Extansions
androidExtensions {
experimental = true
}
}
2.在Activity中導入
kotlinx.android.synthetic.main.佈局名稱.*
代碼如下
import kotlinx.android.synthetic.main.activity_kotlin_test.*
class KotlinTestActivity:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_kotlin_test)
btn_kt_test.text = "button";
}
}
方案三:使用butterknife
butterknife的相關介紹和使用方法可以點擊鏈接進行瀏覽,我想說的是,我目前的項目是一個組件化的項目,使用了ARouter
框架,如果使用butterknife,會有一些問題,處於方便考慮,我組件話的項目中沒采用這一方案。
如果還是想使用的話,推薦看一下下面這個文章的第七部分
Android butterknife在library組件化模塊中的使用問題
總結
1.如果項目中沒有使用Kotlin和ARouter組件話方案,推薦使用Android Studio 3.6新特性
2.如果項目是一個Kotlin項目或者有Kotlin代碼module,可以在java的module中使用Android Studio 3.6新特性,Kotlin使用擴展插件kotlin-android-extensions
3.如果項目是使用ARouter組件化方案的項目的話,不建議使用butterknife