LoginSignup
2
0

【Android】スイッチボタンのつまみの画像をON/OFFで変更

Last updated at Posted at 2021-01-06

まず、つまみ用の画像の設定

thumb_switch.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/sun" android:state_checked="false" />
    <item android:drawable="@drawable/night" android:state_checked="true" />
</selector>

次に、背景設定

background_switch.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="false">
        <shape android:shape="rectangle">
            <solid android:color="@color/white" />
            <corners android:radius="20dp" />
        </shape>
    </item>
    <item android:state_checked="true">
        <shape android:shape="rectangle">
            <solid android:color="@color/black" />
            <corners android:radius="20dp" />
        </shape>
    </item>
</selector>

透明なスタイルに変更

style.xml
    <style name="Switch" parent="Theme.AppCompat.Light">
        <item name="colorControlActivated">#00000000</item>
        <item name="android:colorForeground">#00000000</item>
        <item name="colorControlHighlight">#00000000</item>
    </style>

これらを組み合わせて、スイッチボタンを作成。

switch.xml
<androidx.appcompat.widget.SwitchCompat
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:background="@drawable/background_switch"
	android:theme="@style/SlideButton"
	android:thumb="@drawable/thumb_switch"/>
2
0
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
2
0