Skip to content

Instantly share code, notes, and snippets.

@twaddington
Last active December 14, 2016 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twaddington/a1e84a55e8765ce63d74eaa4bbe63ed3 to your computer and use it in GitHub Desktop.
Save twaddington/a1e84a55e8765ce63d74eaa4bbe63ed3 to your computer and use it in GitHub Desktop.
/*
* Copyright (C) 2017 Simple Finance Technology Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.banksimple.view;
import android.support.annotation.IdRes;
import android.util.SparseArray;
import android.widget.CompoundButton;
/**
* Manager for multiple compound buttons (e.g. {@link android.widget.RadioButton}).
* <p/>
* When a managed button is checked, all others will be unchecked.
*/
public class CompoundButtonContract {
private static final int NONE = -1;
private SparseArray<CompoundButton> mItems;
@IdRes
private int mCheckedId = NONE;
public CompoundButtonContract(CompoundButton... views) {
SparseArray<CompoundButton> items = new SparseArray<>(views.length);
for (CompoundButton v : views) {
items.put(v.getId(), v);
// Listen for changes to the checked state of this button
v.setOnCheckedChangeListener(mOnCheckedChangeListener);
}
mItems = items;
}
public void check(@IdRes int resId) {
CompoundButton button = mItems.get(resId);
if (button != null) {
button.setChecked(true);
}
}
public void clear() {
CompoundButton button = mItems.get(mCheckedId);
if (button != null) {
button.setChecked(false);
}
mCheckedId = NONE;
}
@IdRes
public int getCheckedId() {
return mCheckedId;
}
private final CompoundButton.OnCheckedChangeListener mOnCheckedChangeListener =
new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (!isChecked) {
return; // We only care about newly checked buttons
}
// Uncheck the currently checked button
CompoundButton checked = mItems.get(mCheckedId);
if (checked != null) {
checked.setChecked(false);
}
// Cache the ID of the newly checked button
mCheckedId = buttonView.getId();
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment