2019년 2월 27일 수요일
안드로이드 RecyclerView 예제
- androidx 기준
- 클릭 이벤트, Diffutil 구현 샘플
1. app module dependencies 설정
2019.02.27 기준
implementation 'androidx.recyclerview:recyclerview-selection:1.0.0'
레퍼런스 : https://developer.android.com/jetpack/androidx/migrate
2. DiffUtil.Callback 작성
- DiffUtilCallback
public class DiffUtilCallback extends DiffUtil.Callback {
private final List<TextItem> oldList;
private final List<TextItem> newList;
public DiffUtilCallback(List<TextItem> oldList, List<TextItem> newList) {
this.oldList = oldList;
this.newList = newList;
}
@Override
public int getOldListSize() {
return oldList == null ? 0 : oldList.size();
}
@Override
public int getNewListSize() {
return newList == null ? 0 : newList.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return oldList.get(oldItemPosition).getId() == newList.get(newItemPosition).getId();
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
return oldList.get(oldItemPosition).getText().equals(newList.get(newItemPosition).getText());
}
}
3. RecyclerView.Adapter 구현
- TextItemAdapter
public abstract class TextItemAdapter extends RecyclerView.Adapter<Holder> implements View.OnClickListener {
private final List<TextItem> list = new ArrayList<>();
@Override
public void onClick(View v) {
ViewParent parent = v.getParent();
if (parent instanceof RecyclerView) {
RecyclerView rv = (RecyclerView) parent;
// 클릭된 포지션 찾기
int position = rv.getChildAdapterPosition(v);
TextItem item = list.get(position);
onItemClick(rv, v, position, item);
}
}
/**
* 클릭 이벤트
*
* @param rv
* @param view
* @param position
* @param item
*/
public abstract void onItemClick(RecyclerView rv, View view, int position, TextItem item);
@NonNull
@Override
public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_1, parent, false);
// 클릭 이벤트
view.setOnClickListener(this);
return new Holder(view);
}
@Override
public void onBindViewHolder(@NonNull Holder holder, int position) {
holder.bindItem(list.get(position));
}
@Override
public int getItemCount() {
return list.size();
}
public void updateList(List<TextItem> newList) {
// 리스트 갱신
DiffUtilCallback diffUtilCallback = new DiffUtilCallback(list, newList);
DiffUtil.DiffResult result = DiffUtil.calculateDiff(diffUtilCallback);
this.list.clear();
this.list.addAll(newList);
result.dispatchUpdatesTo(this);
}
}
4. 샘플코드
소스코드
APK
피드 구독하기:
댓글 (Atom)
댓글 없음:
댓글 쓰기