基类Adapter
package com.example.administrator.databindingproject;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
/**
* 设置抽象的BaseAdapter
*
* @param <T> 继承于ViewDataBinding
* @param <M> Model实体类
*/
public abstract class BaseAdapter<T extends ViewDataBinding, M> extends RecyclerView.Adapter {
private List<M> list;
private Context context;
public BaseAdapter(List<M> list, Context context) {
this.list = list;
this.context = context;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflate = LayoutInflater.from(context);
T binding = DataBindingUtil.inflate(inflate, getLayout(), parent, false);
return new MyViewHolder(binding.getRoot());
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
T binding = DataBindingUtil.getBinding(holder.itemView);
setItemData(binding, list.get(position));
}
@Override
public int getItemCount() {
return list.size();
}
//获取item布局
public abstract int getLayout();
//设置viewHolder的数据
public abstract void setItemData(T binding, M m);
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView) {
super(itemView);
}
}
}
在Adapter中继承实现
package com.example.administrator.databindingproject;
import android.content.Context;
import android.util.Log;
import com.example.administrator.databindingproject.databinding.ItemSecondBinding;
import java.util.List;
/**
* Created by $wu on 2017-09-09 下午 2:03.
*/
public class TestAdapter extends BaseAdapter<ItemSecondBinding, User> {
public TestAdapter(List<User> list, Context context) {
super(list, context);
}
@Override
public int getLayout() {
return R.layout.item_second;
}
@Override
public void setItemData(ItemSecondBinding binding, User t) {
binding.setUser(t);
binding.executePendingBindings();
}
}
Activityh中的实现
private void initView() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
List<User> users = new ArrayList<>();
for (int i = 0; i < 30; i++) {
User user = new User();
user.name.set("wu");
user.age.set(i);
users.add(user);
}
TestAdapter adapter = new TestAdapter(users, this);
recyclerView.setAdapter(adapter);
}