1 // Copyright 2018 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 package org.chromium.ui.widget; 6 7 import android.content.Context; 8 import android.graphics.drawable.Drawable; 9 import android.util.AttributeSet; 10 import android.widget.Checkable; 11 12 import androidx.annotation.Nullable; 13 14 /** 15 * ImageView that has checkable state. Checkable state can be used with StateListDrawable and 16 * AnimatedStateListDrawable to dynamically change the appearance of this widget. 17 */ 18 public class CheckableImageView extends ChromeImageView implements Checkable { 19 private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked}; 20 21 private boolean mChecked; 22 CheckableImageView(final Context context, final AttributeSet attrs)23 public CheckableImageView(final Context context, final AttributeSet attrs) { 24 super(context, attrs); 25 } 26 27 @Override onCreateDrawableState(int extraSpace)28 public int[] onCreateDrawableState(int extraSpace) { 29 if (!isChecked()) return super.onCreateDrawableState(extraSpace); 30 int[] drawableState = super.onCreateDrawableState(extraSpace + CHECKED_STATE_SET.length); 31 return mergeDrawableStates(drawableState, CHECKED_STATE_SET); 32 } 33 34 @Override setImageDrawable(@ullable Drawable drawable)35 public void setImageDrawable(@Nullable Drawable drawable) { 36 if (drawable == getDrawable()) return; 37 super.setImageDrawable(drawable); 38 refreshDrawableState(); 39 } 40 41 @Override toggle()42 public void toggle() { 43 setChecked(!mChecked); 44 } 45 46 @Override isChecked()47 public boolean isChecked() { 48 return mChecked; 49 } 50 51 @Override setChecked(final boolean checked)52 public void setChecked(final boolean checked) { 53 if (mChecked == checked) return; 54 mChecked = checked; 55 refreshDrawableState(); 56 } 57 } 58