3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Android】 ToggleButtonのカスタマイズ

Posted at

はじめに

ToggleButtonのアイコンと背景をカスタマイズする方法。
全体の流れとしては、まず前景画像と背景のレイアウトをtoggle.xmlで記述し、次にそれをToggleButtonのbackgroundに指定する。

drawable

state_checkedでON/OFFを切り替える。layer-list内に背景とbitmapを記述。

toggle.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<item android:state_checked="true">
		<layer-list>
			<item>
				<shape>
					<corners android:radius="12dp"/>
					<solid android:color="@color/on"/>
				</shape>
			</item>
			<item android:width="60dp" android:height="60dp" android:drawable="@drawable/check_icon" android:gravity="center"/>
		</layer-list>
	</item>
	<item>
		<layer-list>
			<item>
				<shape>
					<corners android:radius="12dp"/>
					<solid android:color="@color/off"/>
				</shape>
			</item>
			<item android:width="60dp" android:height="60dp" android:drawable="@drawable/clear_icon" android:gravity="center"/>
		</layer-list>
	</item>
</selector>

layout

先ほど作成したtoggle.xmlを背景に定義。textOntextOffをnullにする。

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto"
	xmlns:tools="http://schemas.android.com/tools"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	tools:context=".MainActivity">

	<ToggleButton
		android:id="@+id/toggle_button"
		android:layout_width="80dp"
		android:layout_height="80dp"
		android:background="@drawable/toggle"
		android:textOff="@null"
		android:textOn="@null"
		app:layout_constraintBottom_toBottomOf="parent"
		app:layout_constraintEnd_toEndOf="parent"
		app:layout_constraintStart_toStartOf="parent"
		app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
3
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?