Skip to content

Instantly share code, notes, and snippets.

@Sloaix
Last active March 23, 2017 13:10
Show Gist options
  • Save Sloaix/44054aac26063e5cb63eca0ce106e21d to your computer and use it in GitHub Desktop.
Save Sloaix/44054aac26063e5cb63eca0ce106e21d to your computer and use it in GitHub Desktop.
CompoundButton radio tab切换器
/**
* author:lsxiao
* date:2017-03-23 18:47
* github:https://github.com/lsxiao
* zhihu:https://zhihu.com/people/lsxiao
* <p>
* tab切换器,用于解决CompoundButton不在一同一个父布局下的 radio tab 切换
*/
public class TabSwitcher {
private SparseArrayCompat<CompoundButton> mButtons;
private boolean mProtectFromCheckedChange = false;
private int mCheckedId = -1;
private OnTabCheckedChangedListener mListener;
public TabSwitcher() {
mButtons = new SparseArrayCompat<>();
}
public void init(View view, @IdRes int... ids) {
if (view == null) {
throw new NullPointerException("the view is null");
}
for (int id : ids) {
if (view.findViewById(id) == null) {
throw new IllegalArgumentException("can not find view with id " + id);
}
if (!(view.findViewById(id) instanceof CompoundButton)) {
throw new IllegalArgumentException("the id is not of a compoundButton");
}
CompoundButton compoundButton = (CompoundButton) view.findViewById(id);
add(id, compoundButton);
}
}
private void add(@IdRes int id, final CompoundButton button) {
mButtons.put(id, button);
button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// 避免无限循环
if (mProtectFromCheckedChange) {
return;
}
mProtectFromCheckedChange = true;
if (mCheckedId != -1) {
mButtons.get(mCheckedId).setChecked(false);
}
mProtectFromCheckedChange = false;
int id = buttonView.getId();
setCheckedId(id);
if (mListener != null) {
mListener.onTabCheckedChanged(buttonView, isChecked);
}
}
});
}
public void checked(@IdRes int id) {
if (mButtons.get(id) == null) {
return;
}
if (mCheckedId != -1) {
mButtons.get(mCheckedId).setChecked(false);
}
mButtons.get(id).setChecked(true);
setCheckedId(id);
}
private void setCheckedId(@IdRes int checkedId) {
mCheckedId = checkedId;
}
public void setListener(OnTabCheckedChangedListener listener) {
mListener = listener;
}
public interface OnTabCheckedChangedListener {
void onTabCheckedChanged(CompoundButton button, boolean isChecked);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment