Last active
May 2, 2018 23:01
-
-
Save renanferrari/f37c77ff9f02be222bd9c38ef5d796c6 to your computer and use it in GitHub Desktop.
A checkable ImageView for Android
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.support.annotation.Nullable; | |
import android.support.v7.widget.AppCompatImageView; | |
import android.util.AttributeSet; | |
import android.widget.Checkable; | |
public class CheckableImageView extends AppCompatImageView implements Checkable { | |
private boolean checked; | |
private boolean broadcasting; | |
private OnCheckedChangeListener onCheckedChangeListener; | |
private static final int[] CHECKED_STATE_SET = { | |
android.R.attr.state_checked | |
}; | |
public interface OnCheckedChangeListener { | |
void onCheckedChanged(CheckableImageView checkableImageView, boolean isChecked); | |
} | |
public CheckableImageView(final Context context) { | |
this(context, null); | |
} | |
public CheckableImageView(final Context context, final AttributeSet attrs) { | |
this(context, attrs, 0); | |
} | |
public CheckableImageView(final Context context, final AttributeSet attrs, final int defStyleAttr) { | |
super(context, attrs, defStyleAttr); | |
setOnClickListener(v -> toggle()); | |
} | |
@Override public int[] onCreateDrawableState(final int extraSpace) { | |
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); | |
if (isChecked()) { | |
mergeDrawableStates(drawableState, CHECKED_STATE_SET); | |
} | |
return drawableState; | |
} | |
@Override public void toggle() { | |
setChecked(!checked); | |
} | |
@Override public boolean isChecked() { | |
return checked; | |
} | |
@Override public void setChecked(final boolean checked) { | |
if (this.checked != checked) { | |
this.checked = checked; | |
refreshDrawableState(); | |
// Avoid infinite recursions if setChecked() is called from a listener | |
if (broadcasting) { | |
return; | |
} | |
broadcasting = true; | |
if (onCheckedChangeListener != null) { | |
onCheckedChangeListener.onCheckedChanged(this, checked); | |
} | |
broadcasting = false; | |
} | |
} | |
public void setOnCheckedChangeListener(@Nullable final OnCheckedChangeListener onCheckedChangeListener) { | |
this.onCheckedChangeListener = onCheckedChangeListener; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment