LoginSignup
1
0

More than 1 year has passed since last update.

【Android】Drawableのxml上で画像にTintを適用

Last updated at Posted at 2022-12-01

はじめに

Drawableのxml上で画像にTintを適用する方法について説明。
例えば、RadioButtonToggleButtonなど、ImageButtonが使えない状況で前景と背景を合わせてDrawableを作成した際、レイアウト上でTintを行うと前景・背景両方とも適用されてしまう。そこで、前景のみTintを適用させる方法を説明。

概要

Drawableフォルダ内に作成したxml上で、<bitmap/>タグ内にandroid:tintを指定。

方法

例として、ToggleButtonで説明。
まず、toggle.xmlに前景と背景を記述。

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="80dp"/>
					<solid android:color="@color/background"/>
				</shape>
			</item>
			<item
				android:width="90dp"
				android:height="60dp"
				android:gravity="center">
				<bitmap
					android:src="@drawable/check"
					android:tint="@color/check"/>
			</item>
		</layer-list>
	</item>
	<item>
		<layer-list>
			<item>
				<shape>
					<corners android:radius="80dp"/>
					<solid android:color="@color/background"/>
				</shape>
			</item>
			<item
				android:width="90dp"
				android:height="60dp"
				android:gravity="center">
				<bitmap
					android:src="@drawable/check"
					android:tint="@color/gray"/>
			</item>
		</layer-list>
	</item>
</selector>

先ほど作成したtoggle.xmlandroid:backgroundに設定。

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"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:background="@color/white">

	<ToggleButton
		android:id="@+id/button"
		android:layout_width="160dp"
		android:layout_height="160dp"
		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>

関連記事

1
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
1
0