LoginSignup
18
19

More than 5 years have passed since last update.

ImageViewをCheckableにカスタマイズしたくなる症候群

Posted at

なんでもCheckableにしたくなりますよね

私は、たとえばImageViewやLinearLayoutをトグルボタンにしたくなったりします。

Checkableを実装する

ImageViewをCheckableにして、checkされた時に画像の周りにボーダーを付けるようにします。

CheckableImageView.java
public class CheckableImageView extends ImageView implements Checkable {

    private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};
    private boolean checked = false;

    public CheckableImageView(Context context) {
        super(context);
    }

    public CheckableImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CheckableImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void setChecked(boolean checked) {
        if (this.checked != checked) {
            this.checked = checked;
            refreshDrawableState();
        }
    }

    @Override
    public boolean isChecked() {
        return checked;
    }

    @Override
    public void toggle() {
        setChecked(!checked);
    }

    @Override
    public int[] onCreateDrawableState(int extraSpace) {
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked()) {
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        }
        return drawableState;
    }
}

チェック時にボーダーを表示するスタイルを定義
state_checked="true"の時のスタイルを指定します。

toggle_image_circle.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape android:shape="oval">
            <size android:width="150dp" android:height="150dp" />
            <stroke
                android:width="5dp"
                android:color="#F0F0F0" />
        </shape>
    </item>
</selector>

あとは、layoutで使うだけ

activity_main.xml
# パッケージ名は環境に合わせて変える
<jp.test.views.CheckableImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/sample_image"
    android:background="@drawable/toggle_image_circle"
    android:src="@mipmap/sample_image" />

簡単ですね♪

いろんなビューで実施できるのでお勧めです。

18
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
19