Created
April 15, 2012 21:38
-
-
Save ducky-hong/2394933 to your computer and use it in GitHub Desktop.
Simple container for checked items for the android list view. With the 'Rule', you could control the checked state of a certain item.
This file contains 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
public class CheckedItemData { | |
SparseBooleanArray mCheckedItemStates = new SparseBooleanArray(); | |
LinkedList<Rule> mRules = new LinkedList<Rule>(); | |
public void addRule(Rule rule) { | |
mRules.add(rule); | |
} | |
public int getCount() { | |
return mCheckedItemStates.size(); | |
} | |
public void clear() { | |
mCheckedItemStates.clear(); | |
} | |
public boolean isItemChecked(int id) { | |
return mCheckedItemStates.get(id); | |
} | |
public boolean setItemChecked(int id, boolean value) { | |
boolean oldValue = mCheckedItemStates.get(id); | |
if (oldValue != value) { | |
for (Rule rule : mRules) { | |
if (!rule.apply(id, oldValue)) { | |
return false; | |
} | |
} | |
if (value) { | |
mCheckedItemStates.put(id, value); | |
} else { | |
mCheckedItemStates.delete(id); | |
} | |
return true; | |
} | |
return false; | |
} | |
public boolean toggleItem(int id) { | |
return setItemChecked(id, !isItemChecked(id)); | |
} | |
public int[] getCheckedItemIds() { | |
int count = mCheckedItemStates.size(); | |
int[] result = new int[count]; | |
for (int i = 0; i < count; i++) { | |
result[i] = mCheckedItemStates.keyAt(i); | |
} | |
return result; | |
} | |
public abstract static class Rule { | |
public boolean apply(int id, boolean value) { | |
if (validate(id, value)) { | |
return true; | |
} else { | |
onFailed(id, value); | |
return false; | |
} | |
} | |
protected abstract boolean validate(int id, boolean value); | |
protected abstract void onFailed(int id, boolean value); | |
} | |
public static class Unmodifiable extends Rule { | |
private int[] mTargets; | |
public Unmodifiable(int[] targets) { | |
this.mTargets = targets; | |
} | |
@Override | |
public boolean validate(int id, boolean value) { | |
for (int targetId : mTargets) { | |
if (targetId == id) { | |
return false; | |
} | |
} | |
return true; | |
} | |
@Override | |
public void onFailed(int id, boolean value) { | |
Log.i("Unmodifiable", "You cannot change the state of " + id); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment