Android工具集

DataBind第一篇:使用DataBind创建基类BaseBi

2019-06-22  本文已影响3人  Small_Cake

原文链接:https://www.jianshu.com/p/6aaa38d0948e

1.创建基类,用到了泛型
public abstract class BaseBindFragment<VB extends ViewDataBinding> extends Fragment {
    protected VB mBinding;
    public abstract int setLayout();
    protected abstract void onBindView(View view, ViewGroup container, Bundle savedInstanceState);
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(this.getContext()).inflate(setLayout(), null);
        mBinding = DataBindingUtil.bind(view);
        onBindView(view, container, savedInstanceState);
        return view;
    }
}
2.布局
<?xml version="1.0" encoding="utf-8"?>
<layout>
    <data>
        <variable
            name="user"
            type="com.smallcake.model.User" />
    </data>
    <android.support.design.widget.CoordinatorLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/tv_nickname"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="@={user.nickname}"
            android:textSize="40sp" />
    </android.support.design.widget.CoordinatorLayout>
</layout>
3.使用
//这里的FragmentCoordinatorlayoutTestBinding就是布局文件fragment_coordinatorlayout_test去下划线,然后用骆驼命名法再加上Binding组成
public class CoordinatorLayoutTestFragment extends BaseBindFragment<FragmentCoordinatorlayoutTestBinding> {
    @Override
    public int setLayout() {
        return R.layout.fragment_coordinatorlayout_test;
    }
    @Override
    protected void onBindView(View view, ViewGroup container, Bundle savedInstanceState) {
        mBinding.setUser(DataLocalUtils.getUser());
    }
}

优点:

缺点:

参考:
简单系统学习:Android DataBinding(数据绑定)入门与实战
系列文章:泡在网上的日子Data系列
异常追踪:DataBinding实用指南 文末有说

上一篇下一篇

猜你喜欢

热点阅读