正文
今天我来学习如何在RecyclerView中使用DataBinding
一般我们的RecyclerView是用来显示各种列表的,但是和Activity或Fragment一样,里面有很多findViewById和逻辑代码,我们要减少这种代码,那么就可以使用DataBinding,下面我们将演示如何在RecyclerView中使用DataBinding
新建一个实体类
User.java
package com.yk.jchat.test;
public class User {
private String username;
private int age;
private boolean sex;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
}
新建布局
item_user.xml
<?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="user"
type="com.yk.jchat.model.model.User"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:padding="@dimen/dimen_frame_normal">
<TextView
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/dimen_margin_16dp"
android:ellipsize="end"
android:maxLines="1"
android:text="@{user.username}"
android:textColor="@color/color_text_normal_black"
android:textSize="@dimen/dimen_text_subhead_size" />
</LinearLayout>
</layout>
对应的布局item_user.xml你可以自己定义,需要注意的一点是你定义的布局可以不给控件加id属性,因为我们这里没用到(为什么不用id,待会你就知道了)
新建适配器
UserAdapter.java
package com.yk.jchat.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.yk.jchat.R;
import com.yk.jchat.databinding.ItemContactsBinding;
import com.yk.jchat.model.model.User;
import java.util.List;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private List<User> mList;
public UserAdapter(List<User> list) {
mList=list;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ItemContactsBinding binding = DataBindingUtil.inflate(inflater, R.layout.item_contacts,parent,false);
return new ViewHolder(binding);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
User user = mList.get(position);
holder.getBinding().setContacts(user);
}
@Override
public int getItemCount() {
return mList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private ItemContactsBinding binding;
public ViewHolder(ItemContactsBinding binding) {
super(binding.getRoot());
this.binding = binding;
}
public ItemContactsBinding getBinding(){
return binding;
}
}
}
可以发现,在我们的适配器中没有findViewbyId方法,也没有太多的逻辑
这样,我们的就可以在Activity或Fragment中使用RecyclerView了,是不是很简单啊。好了,今天就到这里。
网友评论