Android-ViewBinding入門

前段時間Google發(fā)現(xiàn)AndroidStudio3.6.1正式版抠璃,這次更新帶來了很多新特性民镜,其中一個值得學(xué)習(xí)的就是ViewBinding

什么是ViewBinding

In most cases, view binding replaces findViewById.

引用官方的說法是踩叭,在大部情況下锨苏,使用ViewBinding替換findViewById耿币。以前如果不使用第三方框架梳杏, 不管怎樣封裝,使用起來還是很不方便(比如找不到控件淹接、控件ID沖突等問題)十性;

怎樣使用ViewBinding

使用條件:
1. Android Studio 3.6 Canary 11+;
2. Gradle插件3.6.1+塑悼;
準(zhǔn)備好了嗎劲适??厢蒜?

在Activity在使用ViewBinding

  1. 模塊的build.xml中添加ViewBinding的支持霞势;
android {
    ...
    viewBinding {
        enabled = true
    }
}

在項目中開啟了ViewBinding后,就會為每一個布局文件生成一對應(yīng)的綁定文件郭怪,如果不需要生成綁定文件支示,只需要在根布局添加:tools:viewBindingIgnore="true"

<LinearLayout
        ...
        tools:viewBindingIgnore="true" >
    ...
</LinearLayout>
  1. 添加一個布局文件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>
  1. 添加一個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);

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

使用起來還是比較簡單的鄙才,運行一下程序看看效果:


image.png

在Fragment在使用ViewBinding

  1. 先添加一個布局文件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>
  1. 添加一個FragmentViewBindingFragment,代碼如下:
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設(shè)置的文本");
        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;
    }
}
  1. 把上面的activity_main.xml攒庵,修改一下嘴纺,用來添加Fragment,修改后代碼如下:
<?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="match_parent"
        android:layout_height="0dp"
        android:gravity="center"
        android:text="Hello World!"
        android:textSize="24sp"
        app:layout_constraintBottom_toTopOf="@id/f_layout"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_weight="1" />

    <View
        android:id="@+id/v_line"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@android:color/darker_gray"
        app:layout_constraintBottom_toTopOf="@+id/f_layout"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_content" />

    <FrameLayout
        android:id="@+id/f_layout"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/tv_content"
        app:layout_constraintVertical_weight="1" />

</androidx.constraintlayout.widget.ConstraintLayout>
  1. 同時把上面的Activity也修改一下浓冒,修改后代碼如下:
public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding viewBinding;

    @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設(shè)置的文本");

        //添加fragment
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction tx = fm.beginTransaction();
        tx.replace(R.id.f_layout, ViewBindingFragment.newInstance());
        tx.commit();
    }
}

運行一下程序看看效果:


image.png

Fragment中使用也是比較簡單的栽渴,如注意的時,在Fragment中使用ViewBinding時稳懒,要在onDestroyView()方法中把binding的引用移除闲擦,不然會引起內(nèi)存泄漏

總結(jié):

  1. 使用起來比較方便,編譯比較快墅冷,而且是官方推薦的纯路;
  2. 目前還不支持布局變量和布局表達(dá)式;
  3. 不支持雙向綁定寞忿,所以只適合一些簡單的使用場境驰唬;
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市腔彰,隨后出現(xiàn)的幾起案子叫编,更是在濱河造成了極大的恐慌,老刑警劉巖霹抛,帶你破解...
    沈念sama閱讀 219,270評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件搓逾,死亡現(xiàn)場離奇詭異,居然都是意外死亡上炎,警方通過查閱死者的電腦和手機恃逻,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,489評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來藕施,“玉大人寇损,你說我怎么就攤上這事∩咽常” “怎么了矛市?”我有些...
    開封第一講書人閱讀 165,630評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長诲祸。 經(jīng)常有香客問我浊吏,道長,這世上最難降的妖魔是什么救氯? 我笑而不...
    開封第一講書人閱讀 58,906評論 1 295
  • 正文 為了忘掉前任找田,我火速辦了婚禮,結(jié)果婚禮上着憨,老公的妹妹穿的比我還像新娘墩衙。我一直安慰自己,他們只是感情好甲抖,可當(dāng)我...
    茶點故事閱讀 67,928評論 6 392
  • 文/花漫 我一把揭開白布漆改。 她就那樣靜靜地躺著,像睡著了一般准谚。 火紅的嫁衣襯著肌膚如雪挫剑。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,718評論 1 305
  • 那天柱衔,我揣著相機與錄音樊破,去河邊找鬼愉棱。 笑死,一個胖子當(dāng)著我的面吹牛捶码,可吹牛的內(nèi)容都是我干的羽氮。 我是一名探鬼主播,決...
    沈念sama閱讀 40,442評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼惫恼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了澳盐?” 一聲冷哼從身側(cè)響起祈纯,我...
    開封第一講書人閱讀 39,345評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎叼耙,沒想到半個月后腕窥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,802評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡筛婉,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,984評論 3 337
  • 正文 我和宋清朗相戀三年簇爆,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片爽撒。...
    茶點故事閱讀 40,117評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡入蛆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出硕勿,到底是詐尸還是另有隱情哨毁,我是刑警寧澤,帶...
    沈念sama閱讀 35,810評論 5 346
  • 正文 年R本政府宣布源武,位于F島的核電站扼褪,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏粱栖。R本人自食惡果不足惜话浇,卻給世界環(huán)境...
    茶點故事閱讀 41,462評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望闹究。 院中可真熱鬧幔崖,春花似錦、人聲如沸跋核。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,011評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽砂代。三九已至蹋订,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間刻伊,已是汗流浹背露戒。 一陣腳步聲響...
    開封第一講書人閱讀 33,139評論 1 272
  • 我被黑心中介騙來泰國打工椒功, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人智什。 一個月前我還...
    沈念sama閱讀 48,377評論 3 373
  • 正文 我出身青樓动漾,卻偏偏與公主長得像,于是被迫代替她去往敵國和親荠锭。 傳聞我的和親對象是個殘疾皇子旱眯,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,060評論 2 355

推薦閱讀更多精彩內(nèi)容