Last active
September 25, 2021 08:43
-
-
Save raviteja83/1628a6f58fc2563209da0e9472a4cc3b to your computer and use it in GitHub Desktop.
A simple adapter to manage selection in recyclerview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.support.v7.widget.RecyclerView; | |
import android.util.SparseBooleanArray; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* Created by Ravi-PC on 04-12-2015. | |
**/ | |
public abstract class SelectableAdapter<VH extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<VH> { | |
private final SparseBooleanArray selectedItems; | |
SelectableAdapter() { | |
selectedItems = new SparseBooleanArray(); | |
} | |
/** | |
* Indicates if the item at position position is selected | |
* @param position Position of the item to check | |
* @return true if the item is selected, false otherwise | |
*/ | |
boolean isSelected(int position) { | |
return getSelectedItems().contains(position); | |
} | |
/** | |
* Toggle the selection status of the item at a given position | |
* @param position Position of the item to toggle the selection status for | |
*/ | |
public void toggleSelection(int position) { | |
if (selectedItems.get(position, false)) { | |
selectedItems.delete(position); | |
} else { | |
selectedItems.put(position, true); | |
} | |
notifyItemChanged(position); | |
} | |
/** | |
* Clear the selection status for all items | |
*/ | |
public void clearSelection() { | |
List<Integer> selection = getSelectedItems(); | |
selectedItems.clear(); | |
for (Integer i : selection) { | |
notifyItemChanged(i); | |
} | |
} | |
/** | |
* Count the selected items | |
* @return Selected items count | |
*/ | |
public int getSelectedItemCount() { | |
return selectedItems.size(); | |
} | |
/** | |
* Indicates the list of selected items | |
* @return List of selected items ids | |
* */ | |
public List<Integer> getSelectedItems() { | |
List<Integer> items = new ArrayList<>(selectedItems.size()); | |
for (int i = 0; i < selectedItems.size(); ++i) { | |
items.add(selectedItems.keyAt(i)); | |
} | |
return items; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment