Skip to content

Instantly share code, notes, and snippets.

@burntcookie90
Last active August 29, 2015 14:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burntcookie90/f0999fb6a46518d655ac to your computer and use it in GitHub Desktop.
Save burntcookie90/f0999fb6a46518d655ac to your computer and use it in GitHub Desktop.
Checkable layout
public class CheckableLinearLayout extends LinearLayout implements Checkable {
private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };
private boolean mChecked;
private OnCheckedChangeListener mOnCheckedChangeListener;
public CheckableLinearLayout(Context context) {
super(context, null);
}
public CheckableLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CheckableLinearLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
mOnCheckedChangeListener = onCheckedChangeListener;
}
/**
* Interface definition for a callback to be invoked when the checked state of a CheckableRelativeLayout changed.
*/
public static interface OnCheckedChangeListener {
public void onCheckedChanged(CheckableLinearLayout layout, boolean isChecked);
}
@Override
public void setChecked(boolean checked) {
mChecked = checked;
refreshDrawableState();
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child instanceof Checkable) {
((Checkable) child).setChecked(mChecked);
}
}
if (mOnCheckedChangeListener != null) {
mOnCheckedChangeListener.onCheckedChanged(this, mChecked);
}
}
@Override
public boolean isChecked() {
return mChecked;
}
@Override
public void toggle() {
setChecked(!mChecked);
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment