Last active
October 3, 2018 07:43
-
-
Save zerobranch/dd5937d3d7eb9afe31a26d612002112f to your computer and use it in GitHub Desktop.
Checkable Linear Layout
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
import android.content.Context; | |
import android.util.AttributeSet; | |
import android.view.View; | |
import android.widget.Checkable; | |
import android.widget.LinearLayout; | |
import java.util.HashSet; | |
import java.util.Set; | |
public class CheckableLinearLayout extends LinearLayout implements Checkable { | |
private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked}; | |
private OnCheckedChangeListener onCheckedChangeListener; | |
private final Set<Checkable> checkableSet = new HashSet<>(); | |
private boolean checked; | |
public CheckableLinearLayout(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
public CheckableLinearLayout(Context context) { | |
this(context, null); | |
} | |
@Override | |
protected void onFinishInflate() { | |
super.onFinishInflate(); | |
final int childCount = getChildCount(); | |
for (int i = 0; i < childCount; ++i) { | |
final View v = getChildAt(i); | |
if (v instanceof Checkable) { | |
checkableSet.add((Checkable) v); | |
} | |
} | |
} | |
@Override | |
public boolean isChecked() { | |
return checked; | |
} | |
@Override | |
public void setChecked(boolean checked) { | |
if (checked == this.checked) { | |
return; | |
} | |
this.checked = checked; | |
for (Checkable checkable : checkableSet) { | |
checkable.setChecked(checked); | |
} | |
refreshDrawableState(); | |
if (onCheckedChangeListener != null) { | |
onCheckedChangeListener.onCheckedChanged(this, checked); | |
} | |
} | |
@Override | |
public void toggle() { | |
setChecked(!checked); | |
} | |
@Override | |
public boolean performClick() { | |
toggle(); | |
return super.performClick(); | |
} | |
@Override | |
public int[] onCreateDrawableState(int extraSpace) { | |
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); | |
if (isChecked()) { | |
mergeDrawableStates(drawableState, CHECKED_STATE_SET); | |
} | |
return drawableState; | |
} | |
public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) { | |
this.onCheckedChangeListener = onCheckedChangeListener; | |
} | |
public interface OnCheckedChangeListener { | |
void onCheckedChanged(CheckableLinearLayout currentView, boolean isChecked); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment