Android ViewBinding基礎

前段時間更新ButterKnife垃帅,被R2給惡心到了漫蛔,所以準備學習一下ViewBinding將ButterKnife替換掉幕袱。

引用

Android-ViewBinding入門
ViewBinding探索

ViewBinding的作用

在大部情況下访得,使用ViewBinding替換findViewById州既。以前如果不使用第三方框架氮凝, 不管怎樣封裝羔巢,使用起來還是很不方便(比如找不到控件、控件ID沖突等問題)

ViewBinding的開啟流程

  • 首先更新AS到3.6版本
  • 打開module的gradle文件
  • 在android函數里面添加如下代碼罩阵,這樣就開啟完成了
android {
    ...
    viewBinding {
        enabled = true
    }
}

ViewBinding的使用

  • 默認情況下布局XML文件都會生成一個 XXXBinding 類
  • 如有不需要生成Binding類的竿秆,可在跟布局添加屬性 tools:viewBindingIgnore="true"如:
<LinearLayout
        ...
        tools:viewBindingIgnore="true" >
    ...
</LinearLayout>
  • 添加一個布局文件activity_main.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=".MainActivity">

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>
  • 接著就可以在Activity里面進行使用 XXXBinding 類稿壁,該類提供了三個初始化函數
fun inflate(inflater: LayoutInflater): XXXBinding
fun inflate(inflater: LayoutInflater, parent: ViewGroup, attachToParent: boolean): XXXBinding
fun bind(view: View): XXXBinding
  • 添加一個ActivityMainActivity.java,代碼如下
public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding viewBinding;//ActivityMainBinding就是上面activity_main.xml生成的綁定文件

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //以前是這樣綁定布局文件的
//        setContentView(R.layout.activity_main);

        //現在是這樣綁定布局文件的
        viewBinding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());
        //在這里設置一個顯示文件
        viewBinding.tvContent.setText("這里是通過ViewBinding設置的文本");
    }
}

運行效果:


ViewBinding運行效果

在Fragment在使用ViewBinding

  • 先添加一個布局文件fragment_view_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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:gravity="center"
        android:text="Hello World!"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_weight="1" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • 添加一個Fragment,ViewBindingFragment,代碼如下:
public class ViewBindingFragment extends Fragment {
    private FragmentViewBindingBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentViewBindingBinding.inflate(inflater, container, false);
        View view = binding.getRoot();
        binding.tvContent.setText("這里是在Fragment通過ViewBinding設置的文本");
        return view;
    }


    public static ViewBindingFragment newInstance() {
        Bundle args = new Bundle();
        ViewBindingFragment fragment = new ViewBindingFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

Fragment中使用注意事項

在Fragment中使用ViewBinding時傅是,要在onDestroyView()方法中把binding的引用移除匪燕,不然會引起內存泄漏;

總結

1.使用起來比較方便喧笔,編譯比較快谎懦,而且是官方推薦的;
2.目前還不支持布局變量和布局表達式溃斋;
3.不支持雙向綁定界拦,所以只適合一些簡單的使用場境;
4.解決了控件空指針的問題

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末梗劫,一起剝皮案震驚了整個濱河市享甸,隨后出現的幾起案子截碴,更是在濱河造成了極大的恐慌,老刑警劉巖蛉威,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件日丹,死亡現場離奇詭異,居然都是意外死亡蚯嫌,警方通過查閱死者的電腦和手機哲虾,發(fā)現死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來择示,“玉大人束凑,你說我怎么就攤上這事≌っぃ” “怎么了汪诉?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵,是天一觀的道長谈秫。 經常有香客問我扒寄,道長,這世上最難降的妖魔是什么拟烫? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任该编,我火速辦了婚禮,結果婚禮上硕淑,老公的妹妹穿的比我還像新娘上渴。我一直安慰自己,他們只是感情好喜颁,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布稠氮。 她就那樣靜靜地躺著,像睡著了一般半开。 火紅的嫁衣襯著肌膚如雪隔披。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天寂拆,我揣著相機與錄音奢米,去河邊找鬼。 笑死纠永,一個胖子當著我的面吹牛鬓长,可吹牛的內容都是我干的。 我是一名探鬼主播尝江,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼涉波,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起啤覆,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤苍日,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后窗声,有當地人在樹林里發(fā)現了一具尸體相恃,經...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年笨觅,在試婚紗的時候發(fā)現自己被綠了拦耐。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡见剩,死狀恐怖杀糯,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情炮温,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布牵舵,位于F島的核電站柒啤,受9級特大地震影響,放射性物質發(fā)生泄漏畸颅。R本人自食惡果不足惜担巩,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望没炒。 院中可真熱鬧涛癌,春花似錦、人聲如沸送火。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽种吸。三九已至弃衍,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間坚俗,已是汗流浹背镜盯。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留猖败,地道東北人速缆。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓,卻偏偏與公主長得像恩闻,于是被迫代替她去往敵國和親艺糜。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內容