if (oldItem.getId() != newItem.getId()) {
return false;
}
return oldItem.getCityName().equals(newItem.getCityName());
}
}
Adapter
部分
public class SortedAdapter extends RecyclerView.Adapter<SortedAdapter.ViewHolder> {
// 数据源使用SortedList
private SortedList mSortedList;
private LayoutInflater mInflater;
public SortedAdapter(Context mContext) {
mInflater = LayoutInflater.from(mContext);
}
public void setSortedList(SortedList mSortedList) {
this.mSortedList = mSortedList;
}
/**
- 批量更新操作,例如:
-
mSortedList.beginBatchedUpdates();
-
try {
-
mSortedList.add(item1)
-
mSortedList.add(item2)
-
mSortedList.remove(item3)
-
...
-
} finally {
-
mSortedList.endBatchedUpdates();
-
}
- */
public void setData(List mData){
mSortedList.beginBatchedUpdates();
mSortedList.addAll(mData);
mSortedList.endBatchedUpdates();
}
public void removeData(int index){
mSortedList.removeItemAt(index);
}
public void clear(){
mSortedList.clear();
}
@Override
@NonNull
public SortedAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(mInflater.inflate(R.layout.item_test, parent, false));
}
@Override
public void onBindViewHolder(@NonNull SortedAdapter.ViewHolder holder, final int position) {
…
}
@Override
public int getItemCount() {
return mSortedList.size();
}
…
}
使用部分:
public class SortedListActivity extends AppCompatActivity {
private SortedAdapter mSortedAdapter;
private int count = 10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sorted_list);
RecyclerView mRecyclerView = findViewById(R.id.rv);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mSortedAdapter = new SortedAdapter(this);
// SortedList初始化
SortedListCallback mSortedListCallback = new SortedListCallback(mSortedAdapter);
SortedList mSortedList = new SortedList<>(City.class, mSortedListCallback);
mSortedAdapter.setSortedList(mSortedList);
mRecyclerView.setAdapter(mSortedAdapter);
updateData();
}
private void addData() {
mSortedAdapter.setData(new City(count, "城市 " + count, “c”));
count ++;
}
private List mList = new ArrayList();
private void updateData() {