Android DatabindAndroid-Data BindingAndroid开发经验谈

Android DataBinding使用详解(二)

2017-07-26  本文已影响461人  容华谢后
封面

《Android DataBinding使用详解(一)》

官方文档

Demo下载地址

1.在RecyclerView中使用DataBinding

Adapter的定义方式和普通方式相同,都是继承了RecyclerView.Adapter<ViewHolder>,然后实现其中的方法,但是具体的实现方式还是有所差别的:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.BindingHolder> {

    private List<RecyclerViewItem> list;

    public RecyclerViewAdapter(List<RecyclerViewItem> list) {
        this.list = list;
    }

    @Override
    public RecyclerViewAdapter.BindingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        AdapterRecyclerViewBinding binding = DataBindingUtil.inflate(
                LayoutInflater.from(parent.getContext()), R.layout.adapter_recycler_view, parent, false);

        BindingHolder holder = new BindingHolder(binding.getRoot());
        holder.setBinding(binding);
        return holder;
    }

    @Override
    public void onBindViewHolder(RecyclerViewAdapter.BindingHolder holder, int position) {
        holder.getBinding().setVariable(BR.item, list.get(position));
        holder.getBinding().executePendingBindings();
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class BindingHolder extends RecyclerView.ViewHolder {

        private AdapterRecyclerViewBinding binding;

        public BindingHolder(View itemView) {
            super(itemView);
        }

        public AdapterRecyclerViewBinding getBinding() {
            return binding;
        }

        public void setBinding(AdapterRecyclerViewBinding binding) {
            this.binding = binding;
        }
    }
}

首先看下BindingHolder,由于使用了DataBinding机制,不需要在Holder中初始化控件了,只需要提供Binding的get和set方法就可以了:

public class BindingHolder extends RecyclerView.ViewHolder {

    private AdapterRecyclerViewBinding binding;

    public BindingHolder(View itemView) {
        super(itemView);
    }

    public AdapterRecyclerViewBinding getBinding() {
        return binding;
    }

    public void setBinding(AdapterRecyclerViewBinding binding) {
        this.binding = binding;
    }
}

在onCreateViewHolder中绑定UI,获取到Binding对象,然后将Binding对象set到Holder中:

@Override
public RecyclerViewAdapter.BindingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    AdapterRecyclerViewBinding binding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.getContext()), R.layout.adapter_recycler_view, parent, false);

    BindingHolder holder = new BindingHolder(binding.getRoot());
    holder.setBinding(binding);
    return holder;
}

在onBindViewHolder方法中,调用Binding的setVariable方法设置UI显示的数据,其中item是RecyclerView内置的变量,如果RecyclerView只使用了一种布局,还可以使用holder.getBinding().setItem(list.get(position));来设置数据。由于数据改变后,DataBinding会在下一帧刷新UI,这样会导致屏幕闪一下,所以还需要调用Binding的executePendingBindings方法立即刷新UI:

@Override
public void onBindViewHolder(RecyclerViewAdapter.BindingHolder holder, int position) {
    holder.getBinding().setVariable(BR.item, list.get(position));
    holder.getBinding().executePendingBindings();
}

adapter_recycler_view布局文件:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="item"
            type="com.yl.databindingdemo.bean.RecyclerViewItem" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:padding="10dp"
            android:text="@{item.content}"
            android:textColor="@color/colorAccent"
            android:textSize="18sp" />

    </RelativeLayout>

</layout>

在Activity中使用:

public class RecyclerViewActivity extends AppCompatActivity {

    private List<RecyclerViewItem> list;

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

        initData();

        ActivityRecyclerViewBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_recycler_view);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(list);
        binding.recyclerView.setAdapter(recyclerViewAdapter);

        // 更新
        updateData();
        recyclerViewAdapter.notifyDataSetChanged();
    }

    private void initData() {
        list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(new RecyclerViewItem(String.valueOf(i)));
        }
    }

    private void updateData() {
        for (int i = 10; i < 20; i++) {
            list.add(new RecyclerViewItem(String.valueOf(i)));
        }
    }
}

activity_recycler_view布局文件:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

</layout>

2.在多布局RecyclerView中使用DataBinding

和普通的多布局Adapter类似,重写getItemViewType方法,然后在onCreateViewHolder方法中根据viewType加载相应的布局,onBindViewHolder方法中不需要再判断Holder类型,直接设置数据然后立即刷新UI即可:

public class MultiRecyclerViewAdapter extends RecyclerView.Adapter<MultiRecyclerViewAdapter.BindingHolder> {

    private List<RecyclerViewItem> list;

    public MultiRecyclerViewAdapter(List<RecyclerViewItem> list) {
        this.list = list;
    }

    @Override
    public int getItemViewType(int position) {
        if (position < 5) {
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    public MultiRecyclerViewAdapter.BindingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        ViewDataBinding binding;

        if (viewType == 0) {
            binding = DataBindingUtil.inflate(
                    LayoutInflater.from(parent.getContext()), R.layout.adapter_recycler_view_other, parent, false);
        } else {
            binding = DataBindingUtil.inflate(
                    LayoutInflater.from(parent.getContext()), R.layout.adapter_recycler_view, parent, false);
        }

        BindingHolder holder = new BindingHolder(binding.getRoot());
        holder.setBinding(binding);
        return holder;
    }

    @Override
    public void onBindViewHolder(MultiRecyclerViewAdapter.BindingHolder holder, int position) {
        holder.getBinding().setVariable(BR.item, list.get(position));
        holder.getBinding().executePendingBindings();
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public class BindingHolder extends RecyclerView.ViewHolder {

        private ViewDataBinding binding;

        public BindingHolder(View itemView) {
            super(itemView);
        }

        public ViewDataBinding getBinding() {
            return binding;
        }

        public void setBinding(ViewDataBinding binding) {
            this.binding = binding;
        }
    }
}

除此之外,还可以通过定义多个Holder的方式来实现。

3.自定义属性

举个栗子,如果你的项目中用到了Glide,或者是其他的图片加载框架,由于这些框架都是通过url给ImageView设置图片的,但是ImageView中并没有设置url的属性,那么该如何使用DataBinding绑定UI呢?这时DataBinding强大的自定义属性功能就派上用场了,一起来看看:

public class ImageUtils {

    /**
     * 加载图片
     * 无需手动调用此方法
     *
     * @param view ImageView
     * @param url  图片地址
     */
    @BindingAdapter({"imageUrl"})
    public static void loadImage(ImageView view, String url) {
        Glide.with(view.getContext()).load(url).into(view);
    }
}

使用@BindingAdapter注解设置自定义属性的名称,如上所示,imageUrl就是属性的名称,当ImageView中使用imageUrl属性时,会自动调用loadImage方法,参数view为当前使用imageUrl属性的View,参数url为图片地址。

布局文件:

<?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">

    <data>

        <variable
            name="url"
            type="String" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!-- 当imageUrl存在时,会自动调用ImageUtils的loadImage方法 -->
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            app:imageUrl="@{url}" />

    </RelativeLayout>

</layout>

Activity中使用:

public class CustomAttributeActivity extends AppCompatActivity {

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

        ActivityCustomAttributeBinding binding = DataBindingUtil.setContentView(this,
                R.layout.activity_custom_attribute);
        binding.setUrl(null);
    }
}

4.ViewStub

在Android开发中,为了提高布局性能,经常使用ViewStub来动态显示UI,在DataBinding中也是支持使用ViewStub的,一起来学习下:

首先在布局文件中定义ViewStub,和普通方式相同:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="clickListener"
            type="android.view.View.OnClickListener" />
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        android:orientation="vertical">

        <ViewStub
            android:id="@+id/view_stub"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout="@layout/layout_include" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:onClick="@{clickListener}"
            android:text="显示ViewStub"
            android:textAllCaps="false" />

    </LinearLayout>

</layout>

在Activity中显示ViewStub:

public class ViewStubActivity extends AppCompatActivity {

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

        final ActivityViewStubBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_view_stub);

        binding.viewStub.setOnInflateListener(new ViewStub.OnInflateListener() {
            @Override
            public void onInflate(ViewStub stub, View inflated) {
                LayoutIncludeBinding viewStubBinding = DataBindingUtil.bind(inflated);
                User user = new User("容华", "谢后");
                viewStubBinding.setUser(user);
            }
        });

        binding.setClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!binding.viewStub.isInflated()) {
                    binding.viewStub.getViewStub().inflate();
                }
            }
        });
    }
}

布局中的ViewStub控件在Binding中会被转换成代理类ViewStubProxy,所以需要调用代理类的getViewStub方法获取到ViewStub控件,然后再调用ViewStub控件的inflate方法显示布局,同时还需要监听ViewStub的OnInflateListener,当布局显示成功后调用DataBindingUtil的bind方法绑定数据。

看下效果:

ViewStub

OK,到这里DataBinding的大部分用法就讲完了,更多用法可以查看官方文档

5.写在最后

源码已托管到GitHub上,欢迎Fork,觉得还不错就Start一下吧!

GitHub传送门

欢迎同学们吐槽评论,如果你觉得本篇博客对你有用,那么就留个言或者点下喜欢吧(^-^)

上一篇下一篇

猜你喜欢

热点阅读