Skip to content

Commit

Permalink
feature: add 'OnSelectCountChangeListener'
Browse files Browse the repository at this point in the history
  • Loading branch information
jrfeng committed Nov 21, 2020
1 parent c354d44 commit a0ff84f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,15 @@ public void setSelectMode(SelectableHelper.SelectMode mode) {
mSelectableHelper.setSelectMode(mode);
}

/**
* 设置一个用于监听 “选中数量” 改变的监听器。
*
* @param listener 监听器,可为 null。为 null 时将清除上次设置的监听器。
*/
public void setOnSelectCountChangeListener(SelectableHelper.OnSelectCountChangeListener listener) {
mSelectableHelper.setOnSelectCountChangeListener(listener);
}

/**
* 查询某个列表项是否已被选中。
*
Expand Down
33 changes: 33 additions & 0 deletions helper/src/main/java/recyclerview/helper/SelectableHelper.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ public class SelectableHelper {
private List<Integer> mSelectedPositions;

private RecyclerView.AdapterDataObserver mAdapterDataObserver;
private OnSelectCountChangeListener mOnSelectCountChangeListener;

public SelectableHelper(@NonNull RecyclerView.Adapter adapter) {
NonNullUtil.requireNonNull(adapter);
Expand Down Expand Up @@ -135,6 +136,16 @@ public void clearSelected() {
for (Integer selectedPosition : mSelectedPositions.subList(0, mSelectedPositions.size())) {
deselect(selectedPosition);
}
notifySelectCountChanged();
}

/**
* 设置一个用于监听 “选中数量” 改变的监听器。
*
* @param listener 监听器,可为 null。为 null 时将清除上次设置的监听器。
*/
public void setOnSelectCountChangeListener(@Nullable OnSelectCountChangeListener listener) {
mOnSelectCountChangeListener = listener;
}

/**
Expand Down Expand Up @@ -206,6 +217,8 @@ public void onItemRangeRemoved(int positionStart, int itemCount) {
mSelectedPositions.add(selectedItem - itemCount);
}
}

notifySelectCountChanged();
}

@Override
Expand Down Expand Up @@ -268,6 +281,7 @@ private void select(int position) {
}

mSelectedPositions.add(position);
notifySelectCountChanged();

if (mRecyclerView == null) {
return;
Expand All @@ -287,6 +301,7 @@ private void deselect(int position) {

// 要手动装箱, 否则调用的是 remove(int):E 方法, 而不是 remove(Object):boolean 方法
mSelectedPositions.remove(Integer.valueOf(position));
notifySelectCountChanged();

if (mRecyclerView == null) {
return;
Expand All @@ -301,6 +316,12 @@ private void deselect(int position) {
}
}

private void notifySelectCountChanged() {
if (mOnSelectCountChangeListener != null) {
mOnSelectCountChangeListener.onSelectCountChanged(mSelectedPositions.size());
}
}

/**
* 选择模式。
*/
Expand All @@ -320,4 +341,16 @@ public interface Selectable {

void onUnselected();
}

/**
* 监听选中数量改变的。
*/
public interface OnSelectCountChangeListener {
/**
* 当选中的列表项的数量发生改变时会回调该方法。
*
* @param selectedCount 当前的选中数量
*/
void onSelectCountChanged(int selectedCount);
}
}

0 comments on commit a0ff84f

Please sign in to comment.