DataBindingAdapter在項(xiàng)目中實(shí)戰(zhàn)

對(duì)于DataBinding不熟悉的小伙伴可以去官網(wǎng)了解下使用教程:https://developer.android.google.cn/topic/libraries/data-binding

這里就不詳細(xì)介紹DataBinding了,接下來我列舉下在項(xiàng)目中常用的結(jié)合不同控件的使用情況,當(dāng)然還有很多控件沒有使用到,在這里就不一一列舉了,后期會(huì)持續(xù)更新上來。

1. ImageView

圖片加載

@BindingAdapter(value = {"url"})
public static void url(ImageView imageView,String url) {
    //此處可以使用圖片請(qǐng)求框架, 例如
    Picasso.get().load(url).error(R.drawable.ic_empty).into(imageView);
}

ImageView中使用BindingAdapter中的value值\color{#0000FF}{url},如何使用,代碼如下:

app:url ="@{網(wǎng)絡(luò)圖片地址}"

圖片層級(jí)設(shè)置

@BindingAdapter(value = {"levels"})
public static void setLevel(ImageView imageView,int levels) {
    imageView.setImageLevel(levels);
}

矢量圖顏色修改

@BindingAdapter(value = {"tints"})
public static void setTints(ImageView imageView, @ColorInt int color) {
    imageView.getDrawable().setTint(color);
}

GIF圖片加載

@BindingAdapter({"asset"})
public static void setImageAssent(GifImageView view, String assent) {
    try {
        GifDrawable gifFromAssets = new GifDrawable(view.getContext().getAssets(), assent);
        view.setImageDrawable(gifFromAssets);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

2. RadioGroup

單選

    <RadioGroup
        ...
        android:orientation="horizontal"
        android:onCheckedChanged="@{(group, buttonId) -> vm.setGroupSpeedIndex(group.indexOfChild(group.findViewById(buttonId)))}"
        >
        <androidx.appcompat.widget.AppCompatRadioButton
           ...
            android:checked="@{vm.parameterBean.speedValue==1}"
            android:text="低"/>
        <androidx.appcompat.widget.AppCompatRadioButton
           ...
            android:checked="@{vm.parameterBean.speedValue==2}"
            android:text="中"/>
        <androidx.appcompat.widget.AppCompatRadioButton
            ...
            android:checked="@{vm.parameterBean.speedValue==3}"
            android:text="高"/>
    </RadioGroup>

viewModel中的方法

    public void setGroupSpeedIndex(int index) {
          parameterBean.getSpeedValue().set(index+1);
    }

獲取的值使用雙向綁定BaseObservable

public class ConfigParameterBean extends BaseObservable {

private ObservableField<Integer>  speedValue;  

public ConfigParameterBean(){
    speedValue  = new ObservableField<>(2);
}

public ObservableField<Integer> getSpeedValue() {
    return speedValue;
}
}

3. SeekBar 同上RadioGroup的用法

    <androidx.appcompat.widget.AppCompatSeekBar
        ...
        android:progress="@={vm.parameterBean.downUpValue}"
        />

4. RecycleView

\color{#0000FF}{app:decoration}屬性是獲取分割線,recycleView中使用如下:

    <androidx.recyclerview.widget.RecyclerView
            ...
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:decoration="@{vm.getItemDecoration()}"
            app:adapter="@{vm.adapter}"
            />

bindingAdapter中的使用:

@BindingAdapter(value = {"decoration"})
public static void setDecoration(RecyclerView recyclerView, RecyclerView.ItemDecoration itemDecoration) {
    recyclerView.addItemDecoration(itemDecoration);
}

ViewModel中的使用:

public RecyclerView.ItemDecoration getItemDecoration(){
    DividerItemDecoration itemDecoration = new DividerItemDecoration(getApplication(), DividerItemDecoration.VERTICAL);
    itemDecoration.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(getApplication(), R.drawable.bg_trans_item_height_10)));
    return itemDecoration;
}
//適配器
public MapAdapter getAdapter(){
    return adapter;
}

5. SwipeRefreshLayout

SwipeRefreshLayoutd控件的使用,\color{#0000FF}{app:colorResIds}加載顏色的設(shè)置,如下:

    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
         ...
        app:colorResIds="@{vm.getColorResId()}"
        app:refreshing="@{vm.isRefreshing}"
        app:onRefreshListener="@{vm::onRefresh}"
        >
       ...
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

bindingAdapter中的使用:

@BindingAdapter(value = {"colorResIds"})
public static void setColorResIds(SwipeRefreshLayout refreshLayout,@ColorRes int... colorInt) {
    refreshLayout.setColorSchemeResources(colorInt);
}

ViewModel中的使用:
\color{#FF0000}{(注意:數(shù)據(jù)加載完成,isRefreshing的值要設(shè)置為false)}

public @ColorRes int[] getColorResId(){
    return new int[]{R.color.purple_200,R.color.purple_500,R.color.purple_700,R.color.teal_200,R.color.teal_700};
}

public MutableLiveData<Boolean> getIsRefreshing() {
    return isRefreshing;
}

6. SmartRefreshLayout

SmartRefreshLayout的使用(目前使用2.0.3版本)

    <com.scwang.smart.refresh.layout.SmartRefreshLayout
        ...
        app:hasMore="@{vm.hasMore}"
        app:refreshing="@{vm.refreshing}"
        app:moreLoading="@{vm.moreLoading}"
        app:onRefreshListener="@{()->vm.onRefresh()}"
        app:onLoadMoreListener="@{()->vm.onLoadMore()}"
        >
        <androidx.recyclerview.widget.RecyclerView
            ...
            />
    </com.scwang.smart.refresh.layout.SmartRefreshLayout>

bindingAdapter中的使用:

@BindingAdapter(value = {"refreshing","moreLoading","hasMore"},requireAll = false)
public static void bindSmartRefreshLayout(SmartRefreshLayout smartLayout, Boolean refreshing, Boolean moreLoading, Boolean hasMore) {
    if (!refreshing) smartLayout.finishRefresh();
    if (!hasMore) smartLayout.finishLoadMoreWithNoMoreData();
    if (!moreLoading) smartLayout.finishLoadMore();
}

@BindingAdapter(value = {"autoRefresh"})
public static void bindSmartRefreshLayout(SmartRefreshLayout smartLayout,boolean autoRefresh) {
    if (autoRefresh) smartLayout.autoRefresh();
}

@BindingAdapter(value = {"onRefreshListener","onLoadMoreListener"},requireAll = false)
public static void bindSmartRefreshLayout(SmartRefreshLayout smartLayout, OnRefreshListener onRefreshListener, OnLoadMoreListener onLoadMoreListener) {
    smartLayout.setOnRefreshListener(onRefreshListener);
    smartLayout.setOnLoadMoreListener(onLoadMoreListener);
}

@BindingAdapter(value = {"refreshing"})
public static void bindSmartRefreshLayout(SwipeRefreshLayout swipeRefreshLayout, Boolean refreshing) {
    swipeRefreshLayout.setRefreshing(refreshing);
}

veiwModel中的使用:

  1. 繼承于BaseViewModelPage,實(shí)現(xiàn)\color{#FF0000}{onRefresh()、onLoadMore()} 方法;
  2. 數(shù)據(jù)加載完成要記得調(diào)用\color{#FF0000}{onRefreshSuccess()、onRefreshError()}方法
  3. autoRefresh()方法未使用,待驗(yàn)證,如果有問題可以告訴我。
@Override
public void onRefresh() {
    super.onRefresh();
    requestData();//數(shù)據(jù)請(qǐng)求
}

@Override
public void onLoadMore() {
    super.onLoadMore();
    requestData();
}

//大家可以根據(jù)自己的需求去處理數(shù)據(jù)加載邏輯
private void requestData() {
    if (null != iViewListener) iViewListener.startLoading();
    //noinspection ConstantConditions
    requestManager.getMessages(getPage().getValue(), 20)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<MessagesBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    
                }

                @Override
                public void onNext(@NonNull MessagesBean success) {
                    if (null != iViewListener)iViewListener.stopLoading();
                    if (null != success.getData() && success.getData().size() > 0) {
                        total = success.getTotalCount();
                        data.addAll(success.getData());
                    }
                    adapter.notifyDataSetChanged();
                    onRefreshSuccess();
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    if (null != iViewListener) iViewListener.stopLoading();
                    adapter.notifyDataSetChanged();
                    onRefreshError();
                }

                @Override
                public void onComplete() {

                }
            });
}

viewModel的基類代碼較多,這里將源碼貼出來

public abstract class BaseViewModelPage<D> extends BaseModel {
private final MutableLiveData<Integer> page = new MutableLiveData<>();       //頁碼
private final MutableLiveData<Boolean> refreshing = new MutableLiveData<>(); //刷新
private final MutableLiveData<Boolean> moreLoading = new MutableLiveData<>();//加載更多
private final MutableLiveData<Boolean> hasMore = new MutableLiveData<>();    //是否全部加載
private final MutableLiveData<Boolean> autoRefresh = new MutableLiveData<>();//自動(dòng)刷新
protected final List<D> data = new ArrayList<>();  //數(shù)據(jù)集合
protected int total = 0;                           //數(shù)據(jù)總數(shù)

public BaseViewModelPage(@NonNull Application application) {
    super(application);
    page.setValue(0);
    refreshing.setValue(true);
    moreLoading.setValue(true);
    hasMore.setValue(true);
    autoRefresh.setValue(false);
}

@CallSuper
public void onLoadMore() {
    page.setValue(page.getValue()==null?0: page.getValue()+1);
    if (refreshing.getValue())refreshing.setValue(false);
    if (!moreLoading.getValue())moreLoading.setValue(true);
}

@CallSuper
public void onRefresh() {
    page.setValue(0);
    refreshing.setValue(true);
    if (data.size()>0) data.clear();
    if (moreLoading.getValue()) moreLoading.setValue(false);
    if (!hasMore.getValue()) hasMore.setValue(true);
}

@CallSuper
public void autoRefresh() {
    autoRefresh.setValue(true);
}

public MutableLiveData<Integer> getPage() {
    return page;
}

public MutableLiveData<Boolean> getHasMore() {
    return hasMore;
}

public MutableLiveData<Boolean> getRefreshing() {
    return refreshing;
}

public MutableLiveData<Boolean> getMoreLoading() {
    return moreLoading;
}

public MutableLiveData<Boolean> getAutoRefresh() {
    return autoRefresh;
}

protected void onRefreshSuccess(){
    if (page.getValue() == 0) {
        if (refreshing.getValue()) refreshing.setValue(false);
    } else {
        if (data.size()>= total) {
            if (hasMore.getValue()) hasMore.setValue(false);
        } else {
            if (!hasMore.getValue()) hasMore.setValue(true);
        }
        if (moreLoading.getValue())moreLoading.setValue(false);
    }
}

protected void onRefreshError() {
    if (page.getValue() == 0) {
        if (!refreshing.getValue()) refreshing.setValue(true);
    } else {
        if (data.size()>= total) {
            if (hasMore.getValue()) hasMore.setValue(false);
        } else {
            if (!hasMore.getValue()) hasMore.setValue(true);
        }
        if (moreLoading.getValue())moreLoading.setValue(false);
    }
}

//重寫父類的方法子類也需要調(diào)用時(shí)使用
@CallSuper
@Override
public void onCleared() {
    super.onCleared();
}
}

最后,希望對(duì)大家有所幫助,如果有不足的地方歡迎大家指正,謝謝。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容