最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android淺析viewBinding和DataBinding

 更新時(shí)間:2022年09月15日 09:02:15   作者:FranzLiszt1847  
這篇文章主要介紹了Android淺析viewBinding和DataBinding,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下

viewBinding

優(yōu)點(diǎn)

當(dāng)一個(gè)頁(yè)面布局出現(xiàn)多個(gè)控件時(shí),使用findViewById去進(jìn)行控件綁定,過(guò)于冗長(zhǎng),且存在NULL指針異常風(fēng)險(xiǎn)。viewBinding直接創(chuàng)建對(duì)視圖的引用,不存在因控件ID不存在而引發(fā)的NULL指針異常。并且在綁定類中對(duì)控件添加@NonNull注解

findViewByIdviewBinding
冗長(zhǎng)簡(jiǎn)短
NULLNULL安全

配置

3.6之前的版本在build.gradle文件中聲明如下定義

 viewBinding {
            enabled = true
        }

4.0以上的版本在build.gradle文件中聲明如下定義

 buildFeatures {
            viewBinding = true
        }

聲明如上定義之后,點(diǎn)擊同步(Sync Now)按鈕,系統(tǒng)會(huì)自動(dòng)生成viewBinding類,例如MainActivity會(huì)生成名為ActivityMainBinding的類,ReceiveActivity會(huì)生成名為ActivityReceiveBinding的類,以此類推;
以上viewBinding類會(huì)生成在如下路徑文件中

build//generated//data_binding_base_class_source_out//debug//out//com.你的包名//databinding

使用

使用步驟很簡(jiǎn)單,需要被調(diào)用的控件聲明id就行,然后聲明viewBinding類對(duì)象

private ActivityMainBinding binding;

綁定視圖:

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

控件引用:

binding.postMes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this,ReceiverActivity.class));
            }
        });

源碼解析

如上所示,我們使用了ActivityMainBinding.inflate()方法進(jìn)行視圖綁定和binding.getRoot()方法獲取視圖。
首先我們?cè)谕獠客ㄟ^(guò)調(diào)用ActivityMainBinding.inflate()方法。

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater) {
    return inflate(inflater, null, false);
  }

然后內(nèi)部進(jìn)行重載,添加我們的Avcivity的布局文件,并調(diào)研bind(root)方法

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater,
      @Nullable ViewGroup parent, boolean attachToParent) {
    View root = inflater.inflate(R.layout.activity_main, parent, false);
    if (attachToParent) {
      parent.addView(root);
    }
    return bind(root);
  }

在bind方法中進(jìn)行控件綁定,通過(guò)其findChildViewById()方法

@NonNull
  public static ActivityMainBinding bind(@NonNull View rootView) {
    // The body of this method is generated in a way you would not otherwise write.
    // This is done to optimize the compiled bytecode for size and performance.
    int id;
    missingId: {
      id = R.id.content;
      TextView content = ViewBindings.findChildViewById(rootView, id);
      if (content == null) {
        break missingId;
      }

      id = R.id.postMes;
      Button postMes = ViewBindings.findChildViewById(rootView, id);
      if (postMes == null) {
        break missingId;
      }
      return new ActivityMainBinding((LinearLayout) rootView, content, postMes);
    }
    String missingId = rootView.getResources().getResourceName(id);
    throw new NullPointerException("Missing required view with ID: ".concat(missingId));
  }

然后在findChildViewById()方法中最終也使用到了findViewById()方法,但差距在于跳過(guò)視圖本身

 /**
     * Like `findViewById` but skips the view itself.
     *
     * @hide
     */
    @Nullable
    public static <T extends View> T findChildViewById(View rootView, @IdRes int id) {
        if (!(rootView instanceof ViewGroup)) {
            return null;
        }
        final ViewGroup rootViewGroup = (ViewGroup) rootView;
        final int childCount = rootViewGroup.getChildCount();
        for (int i = 0; i < childCount; i++) {
            final T view = rootViewGroup.getChildAt(i).findViewById(id);
            if (view != null) {
                return view;
            }
        }
        return null;
    }

最后通過(guò)將獲取到的控件定義與內(nèi)部定義的字段進(jìn)行縫合,以暴露給外部使用

  @NonNull
  private final LinearLayout rootView;

  @NonNull
  public final TextView content;

  @NonNull
  public final Button postMes;
  private ActivityMainBinding(@NonNull LinearLayout rootView, @NonNull TextView content,
      @NonNull Button postMes) {
    this.rootView = rootView;
    this.content = content;
    this.postMes = postMes;
  }

DataBinding

配置

依舊在build.gradle文件中配置如下定義:

 dataBinding {
            enabled = true
        }

創(chuàng)建實(shí)體類

實(shí)體類通過(guò)繼承BaseObservable類,而BaseObservable又實(shí)現(xiàn)了Observable,從而獲取添加和移除監(jiān)聽的機(jī)制。
在get()方法中使用@Bindable注解,會(huì)自動(dòng)生成BR類,此類中將添加@Bindable的字段聲明成常量,然后在set()方法使用notifyPropertyChanged()配合使用,當(dāng)數(shù)據(jù)發(fā)生變化時(shí),dataBinding會(huì)自動(dòng)修改該字段的值。

public class EventMessage extends BaseObservable {
    public String title;
    public EventMessage(){

    }
    public EventMessage(String title){
        this.title = title;
    }
    @Bindable
    public String getTitle() {
        return title;
    }
    /**
     * @param title*/
    public void setTitle(String title) {
        this.title = title;
        notifyPropertyChanged(BR.title);
    }
}

創(chuàng)建布局

創(chuàng)建layout標(biāo)簽布局才會(huì)生成ActivityMainBinding(以及布局文件名而定)
EditText通過(guò)使用如下定義進(jìn)行綁定,

 android:text="@={viewModel.message.title}"

Button通過(guò)如下定義進(jìn)行點(diǎn)擊事件監(jiān)聽

 android:onClick="@{viewModel.setText}"

以上兩者的存在差距,EditText多了一個(gè)=,而Button沒(méi)有,并且Button綁定監(jiān)聽事件,不需要加()

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <data>
        <variable
            name="viewModel"
            type="com.franzliszt.databinding.ViewModel" />

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity"
        android:orientation="vertical"
        android:gravity="center">
        <EditText
            android:id="@+id/inputText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:hint="default"
            android:text="@={viewModel.message.title}"/>
        <TextView
            android:id="@+id/ShowText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="update"
            android:onClick="@{viewModel.setText}"/>
    </LinearLayout>
</layout>

創(chuàng)建viewModel

通過(guò)監(jiān)聽Button點(diǎn)擊事件,在其中監(jiān)聽EditText輸入事件,并將其輸入的字符串顯示在TextView中

public class ViewModel {
    private ActivityMainBinding binding;
    public EventMessage message;
    public ViewModel(ActivityMainBinding binding, EventMessage message){
        this.binding = binding;
        this.message = message;
    }
    public void setText(View view){
        String str = message.getTitle();
        binding.ShowText.setText(str);
    }
}

dataBinding綁定

 private ActivityMainBinding binding;
binding = DataBindingUtil.setContentView( this,R.layout.activity_main );
binding.setViewModel(new ViewModel(binding,new EventMessage()));

到此這篇關(guān)于Android淺析viewBinding和DataBinding的文章就介紹到這了,更多相關(guān)Android viewBinding 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Android實(shí)現(xiàn)水波紋效果

    Android實(shí)現(xiàn)水波紋效果

    這篇文章主要介紹了Android實(shí)現(xiàn)水波紋效果的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-10-10
  • Android獲取應(yīng)用程序大小和緩存的實(shí)例代碼

    Android獲取應(yīng)用程序大小和緩存的實(shí)例代碼

    這篇文章主要介紹了Android獲取應(yīng)用程序大小和緩存的實(shí)例代碼的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-10-10
  • Android開發(fā)ImageView圖片無(wú)法顯示解決過(guò)程

    Android開發(fā)ImageView圖片無(wú)法顯示解決過(guò)程

    在Android中ImageView無(wú)法顯示加載的本地SDCard圖片:過(guò)程為先調(diào)用本地照相機(jī)程序攝像,然后將拍攝的圖片加載在ImageView中顯示,具體解決方法如下,感興趣的朋友可以參考下哈
    2013-06-06
  • android通用xml解析方法

    android通用xml解析方法

    之前做的網(wǎng)絡(luò)相關(guān)的應(yīng)用,里面涉及到了xml的解析,由于急于完成任務(wù)也沒(méi)有設(shè)計(jì)就直接敲代碼。這幾天給一個(gè)朋友做項(xiàng)目的時(shí)候也涉及到了xml的解析,而且解析的內(nèi)容比較多,我查看了以前的項(xiàng)目中的相關(guān)代碼,頓時(shí)覺得很多代碼都是可以優(yōu)化的。在此寫兩個(gè)通用的xml解析方法,當(dāng)然這里所講的通用只是在一定程度上并且需要遵守一些規(guī)范。
    2013-03-03
  • Android實(shí)現(xiàn)拼圖游戲

    Android實(shí)現(xiàn)拼圖游戲

    這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)拼圖小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Android  TextView中部分文字高亮顯示

    Android TextView中部分文字高亮顯示

    這篇文章主要介紹了Android TextView中部分文字高亮顯示的相關(guān)資料,需要的朋友可以參考下
    2017-07-07
  • Android 藍(lán)牙開發(fā)實(shí)例解析

    Android 藍(lán)牙開發(fā)實(shí)例解析

    本文主要介紹Android 藍(lán)牙開發(fā),這里提供實(shí)例代碼和詳細(xì)解析實(shí)現(xiàn)方法,對(duì)開發(fā)Android藍(lán)牙開發(fā)的朋友提供簡(jiǎn)單示例,有需要的朋友可以參考下
    2016-08-08
  • android RecyclerView添加footerview詳解

    android RecyclerView添加footerview詳解

    大家好,本篇文章主要講的是android RecyclerView添加footerview詳解,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下
    2022-01-01
  • Android中獲取sha1證書指紋數(shù)據(jù)的方法

    Android中獲取sha1證書指紋數(shù)據(jù)的方法

    大家都知道在Android開發(fā)中,經(jīng)常要獲取sha1證書指紋,所以這篇文章主要介紹在Android中如何使用命令獲取sha1證書指紋數(shù)據(jù)的方法,有需要的可以參考借鑒。
    2016-09-09
  • android中AutoCompleteTextView的簡(jiǎn)單用法(實(shí)現(xiàn)搜索歷史)

    android中AutoCompleteTextView的簡(jiǎn)單用法(實(shí)現(xiàn)搜索歷史)

    本篇文章主要介紹了android中AutoCompleteTextView的簡(jiǎn)單用法(自動(dòng)提示),有需要的可以了解一下。
    2016-11-11

最新評(píng)論

邹平县| 临颍县| 威信县| 兴和县| 五大连池市| 聂拉木县| 清镇市| 高碑店市| 镇康县| 绥滨县| 乌拉特中旗| 宁南县| 师宗县| 抚州市| 五原县| 高邮市| 锦屏县| 邢台县| 桂林市| 许昌市| 琼中| 郴州市| 六安市| 罗甸县| 尼木县| 桑日县| 金华市| 浙江省| 湘西| 北流市| 安阳县| 黄梅县| 孟州市| 西青区| 远安县| 美姑县| 长治市| 哈密市| 武鸣县| 周宁县| 西盟|