class TestBean implements Cloneable {
private String name;
private String desc;
....//get set方法省略
//仅写DEMO 用 实现克隆方法
@Override
public TestBean clone() throws CloneNotSupportedException {
TestBean bean = null;
try {
bean = (TestBean) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return bean;
}
public class DiffAdapter extends RecyclerView.Adapter<DiffAdapter.DiffVH> {
private final static String TAG = "zxt";
private List<TestBean> mDatas;
private Context mContext;
private LayoutInflater mInflater;
public DiffAdapter(Context mContext, List<TestBean> mDatas) {
this.mContext = mContext;
this.mDatas = mDatas;
mInflater = LayoutInflater.from(mContext);
}
public void setDatas(List<TestBean> mDatas) {
this.mDatas = mDatas;
}
@Override
public DiffVH onCreateViewHolder(ViewGroup parent, int viewType) {
return new DiffVH(mInflater.inflate(R.layout.item_diff, parent, false));
}
@Override
public void onBindViewHolder(final DiffVH holder, final int position) {
TestBean bean = mDatas.get(position);
holder.tv1.setText(bean.getName());
holder.tv2.setText(bean.getDesc());
holder.iv.setImageResource(bean.getPic());
}
@Override
public int getItemCount() {
return mDatas != null ? mDatas.size() : 0;
}
class DiffVH extends RecyclerView.ViewHolder {
TextView tv1, tv2;
ImageView iv;
public DiffVH(View itemView) {
super(itemView);
tv1 = (TextView) itemView.findViewById(R.id.tv1);
tv2 = (TextView) itemView.findViewById(R.id.tv2);
iv = (ImageView) itemView.findViewById(R.id.iv);
}
}
}
public class MainActivity extends AppCompatActivity {
private List<TestBean> mDatas;
private RecyclerView mRv;
private DiffAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
mRv = (RecyclerView) findViewById(R.id.rv);
mRv.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new DiffAdapter(this, mDatas);
mRv.setAdapter(mAdapter);
}
private void initData() {
mDatas = new ArrayList<>();
mDatas.add(new TestBean("张旭童1", "Android", R.drawable.pic1));
mDatas.add(new TestBean("张旭童2", "Java", R.drawable.pic2));
mDatas.add(new TestBean("张旭童3", "背锅", R.drawable.pic3));
mDatas.add(new TestBean("张旭童4", "手撕产品", R.drawable.pic4));
mDatas.add(new TestBean("张旭童5", "手撕测试", R.drawable.pic5));
}
/**
* 模拟刷新操作
*
* @param view
*/
public void onRefresh(View view) {
try {
List<TestBean> newDatas = new ArrayList<>();
for (TestBean bean : mDatas) {
newDatas.add(bean.clone());//clone一遍旧数据 ,模拟刷新操作
}
newDatas.add(new TestBean("赵子龙", "帅", R.drawable.pic6));//模拟新增数据
newDatas.get(0).setDesc("Android+");
newDatas.get(0).setPic(R.drawable.pic7);//模拟修改数据
TestBean testBean = newDatas.get(1);//模拟数据位移
newDatas.remove(testBean);
newDatas.add(testBean);
//别忘了将新数据给Adapter
mDatas = newDatas;
mAdapter.setDatas(mDatas);
mAdapter.notifyDataSetChanged();//以前我们大多数情况下只能这样
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" > <android.support.v7.widget.RecyclerView android:id="@+id/rv" /> <Button android:id="@+id/btnRefresh" android:layout_alignParentRight="true" android:onClick="onRefresh" android:text="模拟刷新" /> </RelativeLayout>
public abstract static class Callback {
public abstract int getOldListSize();//老数据集size
public abstract int getNewListSize();//新数据集size
public abstract boolean areItemsTheSame(int oldItemPosition, int newItemPosition);//新老数据集在同一个postion的Item是否是一个对象?(可能内容不同,如果这里返回true,会调用下面的方法)
public abstract boolean areContentsTheSame(int oldItemPosition, int newItemPosition);//这个方法仅仅是上面方法返回ture才会调用,我的理解是只有notifyItemRangeChanged()才会调用,判断item的内容是否有变化
//该方法在DiffUtil高级用法中用到 ,暂且不提
@Nullable
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
return null;
}
}
/**
* 介绍:核心类 用来判断 新旧Item是否相等
* 作者:zhangxutong
* 邮箱:zhangxutong@imcoming.com
* 时间: 2016/9/12.
*/
public class DiffCallBack extends DiffUtil.Callback {
private List<TestBean> mOldDatas, mNewDatas;//看名字
public DiffCallBack(List<TestBean> mOldDatas, List<TestBean> mNewDatas) {
this.mOldDatas = mOldDatas;
this.mNewDatas = mNewDatas;
}
//老数据集size
@Override
public int getOldListSize() {
return mOldDatas != null ? mOldDatas.size() : 0;
}
//新数据集size
@Override
public int getNewListSize() {
return mNewDatas != null ? mNewDatas.size() : 0;
}
/**
* Called by the DiffUtil to decide whether two object represent the same Item.
* 被DiffUtil调用,用来判断 两个对象是否是相同的Item。
* For example, if your items have unique ids, this method should check their id equality.
* 例如,如果你的Item有唯一的id字段,这个方法就 判断id是否相等。
* 本例判断name字段是否一致
*
* @param oldItemPosition The position of the item in the old list
* @param newItemPosition The position of the item in the new list
* @return True if the two items represent the same object or false if they are different.
*/
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return mOldDatas.get(oldItemPosition).getName().equals(mNewDatas.get(newItemPosition).getName());
}
/**
* Called by the DiffUtil when it wants to check whether two items have the same data.
* 被DiffUtil调用,用来检查 两个item是否含有相同的数据
* DiffUtil uses this information to detect if the contents of an item has changed.
* DiffUtil用返回的信息(true false)来检测当前item的内容是否发生了变化
* DiffUtil uses this method to check equality instead of {@link Object#equals(Object)}
* DiffUtil 用这个方法替代equals方法去检查是否相等。
* so that you can change its behavior depending on your UI.
* 所以你可以根据你的UI去改变它的返回值
* For example, if you are using DiffUtil with a
* {@link android.support.v7.widget.RecyclerView.Adapter RecyclerView.Adapter}, you should
* return whether the items‘ visual representations are the same.
* 例如,如果你用RecyclerView.Adapter 配合DiffUtil使用,你需要返回Item的视觉表现是否相同。
* This method is called only if {@link #areItemsTheSame(int, int)} returns
* {@code true} for these items.
* 这个方法仅仅在areItemsTheSame()返回true时,才调用。
* @param oldItemPosition The position of the item in the old list
* @param newItemPosition The position of the item in the new list which replaces the
* oldItem
* @return True if the contents of the items are the same or false if they are different.
*/
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
TestBean beanOld = mOldDatas.get(oldItemPosition);
TestBean beanNew = mNewDatas.get(newItemPosition);
if (!beanOld.getDesc().equals(beanNew.getDesc())) {
return false;//如果有内容不同,就返回false
}
if (beanOld.getPic() != beanNew.getPic()) {
return false;//如果有内容不同,就返回false
}
return true; //默认两个data内容是相同的
}
//文艺青年新宠 //利用DiffUtil.calculateDiff()方法,传入一个规则DiffUtil.Callback对象,和是否检测移动item的 boolean变量,得到DiffUtil.DiffResult 的对象 DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffCallBack(mDatas, newDatas), true); //利用DiffUtil.DiffResult对象的dispatchUpdatesTo()方法,传入RecyclerView的Adapter,轻松成为文艺青年 diffResult.dispatchUpdatesTo(mAdapter); //别忘了将新数据给Adapter mDatas = newDatas; mAdapter.setDatas(mDatas);
public void dispatchUpdatesTo(final RecyclerView.Adapter adapter) {
dispatchUpdatesTo(new ListUpdateCallback() {
@Override
public void onInserted(int position, int count) {
adapter.notifyItemRangeInserted(position, count);
}
@Override
public void onRemoved(int position, int count) {
adapter.notifyItemRangeRemoved(position, count);
}
@Override
public void onMoved(int fromPosition, int toPosition) {
adapter.notifyItemMoved(fromPosition, toPosition);
}
@Override
public void onChanged(int position, int count, Object payload) {
adapter.notifyItemRangeChanged(position, count, payload);
}
});
}
/**
* Called by RecyclerView to display the data at the specified position. This method
* should update the contents of the {@link ViewHolder#itemView} to reflect the item at
* the given position.
* <p>
* Note that unlike {@link android.widget.ListView}, RecyclerView will not call this method
* again if the position of the item changes in the data set unless the item itself is
* invalidated or the new position cannot be determined. For this reason, you should only
* use the <code>position</code> parameter while acquiring the related data item inside
* this method and should not keep a copy of it. If you need the position of an item later
* on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will
* have the updated adapter position.
* <p>
* Partial bind vs full bind:
* <p>
* The payloads parameter is a merge list from {@link #notifyItemChanged(int, Object)} or
* {@link #notifyItemRangeChanged(int, int, Object)}. If the payloads list is not empty,
* the ViewHolder is currently bound to old data and Adapter may run an efficient partial
* update using the payload info. If the payload is empty, Adapter must run a full bind.
* Adapter should not assume that the payload passed in notify methods will be received by
* onBindViewHolder(). For example when the view is not attached to the screen, the
* payload in notifyItemChange() will be simply dropped.
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter‘s data set.
* @param payloads A non-null list of merged payloads. Can be empty list if requires full
* update.
*/
public void onBindViewHolder(VH holder, int position, List<Object> payloads) {
onBindViewHolder(holder, position);
}
/**
* When {@link #areItemsTheSame(int, int)} returns {@code true} for two items and
* {@link #areContentsTheSame(int, int)} returns false for them, DiffUtil
* calls this method to get a payload about the change.
*
* 当{@link #areItemsTheSame(int, int)} 返回true,且{@link #areContentsTheSame(int, int)} 返回false时,DiffUtils会回调此方法,
* 去得到这个Item(有哪些)改变的payload。
*
* For example, if you are using DiffUtil with {@link RecyclerView}, you can return the
* particular field that changed in the item and your
* {@link android.support.v7.widget.RecyclerView.ItemAnimator ItemAnimator} can use that
* information to run the correct animation.
*
* 例如,如果你用RecyclerView配合DiffUtils,你可以返回 这个Item改变的那些字段,
* {@link android.support.v7.widget.RecyclerView.ItemAnimator ItemAnimator} 可以用那些信息去执行正确的动画
*
* Default implementation returns {@code null}. * 默认的实现是返回null
*
* @param oldItemPosition The position of the item in the old list
* @param newItemPosition The position of the item in the new list
* @return A payload object that represents the change between the two items.
* 返回 一个 代表着新老item的改变内容的 payload对象,
*/
@Nullable
@Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
//实现这个方法 就能成为文艺青年中的文艺青年
// 定向刷新中的部分更新
// 效率最高
//只是没有了ItemChange的白光一闪动画,(反正我也觉得不太重要)
TestBean oldBean = mOldDatas.get(oldItemPosition);
TestBean newBean = mNewDatas.get(newItemPosition);
//这里就不用比较核心字段了,一定相等
Bundle payload = new Bundle();
if (!oldBean.getDesc().equals(newBean.getDesc())) {
payload.putString("KEY_DESC", newBean.getDesc());
}
if (oldBean.getPic() != newBean.getPic()) {
payload.putInt("KEY_PIC", newBean.getPic());
}
if (payload.size() == 0)//如果没有变化 就传空
return null;
return payload;//
}
@Override
public void onBindViewHolder(DiffVH holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
onBindViewHolder(holder, position);
} else {
//文艺青年中的文青
Bundle payload = (Bundle) payloads.get(0);
TestBean bean = mDatas.get(position);
for (String key : payload.keySet()) {
switch (key) {
case "KEY_DESC":
//这里可以用payload里的数据,不过data也是新的 也可以用
holder.tv2.setText(bean.getDesc());
break;
case "KEY_PIC":
holder.iv.setImageResource(payload.getInt(key));
break;
default:
break;
}
}
}
}
private static final int H_CODE_UPDATE = 1;
private List<TestBean> mNewDatas;//增加一个变量暂存newList
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case H_CODE_UPDATE:
//取出Result
DiffUtil.DiffResult diffResult = (DiffUtil.DiffResult) msg.obj;
diffResult.dispatchUpdatesTo(mAdapter);
//别忘了将新数据给Adapter
mDatas = mNewDatas;
mAdapter.setDatas(mDatas);
break;
}
}
};
new Thread(new Runnable() {
@Override
public void run() {
//放在子线程中计算DiffResult
DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new DiffCallBack(mDatas, mNewDatas), true);
Message message = mHandler.obtainMessage(H_CODE_UPDATE);
message.obj = diffResult;//obj存放DiffResult
message.sendToTarget();
}
}).start();
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有