使用ViewBinding替代findViewById

在使用Java開發Android程序時,總是要寫一大堆的findViewById。後來有了一些諸如ButterKnife之類的,專門用於對findViewById的用法進行簡化,但是ButterKnife還是要通過註解來讓控件與資源id之間進行綁定,並不算是非常方便。隨着kotlin的流行,kotlin-android-extensions插件很好的解決了這個問題。或者是出於性能的考慮,這個插件也被掛上了deprecated的標籤,官方推薦使用ViewBinding來進行替代。目前ViewBinding是我們捨棄findViewById的最佳解決方案,它不僅支持Kotlin同樣也支持Java.

注意事項

第一,確保你的Android Studio是3.6或更高的版本。
第二,在你項目工程模塊的build.gradle中加入以下配置:

android {
    ...
    buildFeatures {
        viewBinding true
    }
}

如何使用

啓動了ViewBinding功能後,Android Studio會自動爲我們所編寫的每一個佈局文件都生成一個對應的Binding類。

Binding類的命名規則是將佈局文件按駝峯方式重命名後,再加上Binding作爲結尾。

比如說,前面我們定義了一個activity_main.xml佈局,那麼與它對應的Binding類就是ActivityMainBinding。

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

如果有些佈局文件你不希望爲它生成對應的Binding類,可以在該佈局文件的根元素位置加入如下聲明:

<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    ...
    tools:viewBindingIgnore="true">
    ...
</LinearLayout>

如何在include和merge的佈局中使用ViewBinding

include

比如我們有個bottom_layout.xml通用底部佈局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:id="@+id/rx"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="版權所有"/>
</LinearLayout>

在我們的activity_main.xml中引用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context=".MainActivity">
    ...
    <include layout="@layout/bottom_layout" android:id="@+id/page_bottom"/>
</LinearLayout>

注意,要給include里加一個id否則找不到。
此時我們就可以在MainActivity中引用到binding.pageBottom.rx.setText("R");

merge

由於merge沒有根view,所以沒辦法設置id,所以只能設置兩個binding來實現

binding = ActivityMainBinding.inflate(layoutInflater);//原binding
mergeBinding = MergeLayoutBinding.bind(binding.root);//merge進來的binding,xml名稱爲merge_layout.xml
setContentView(binding.root);

mergeBinding.mtextview.setText("merge1");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章