🎨
【Android】テーマカラーの変更画面でよくみる色が付いた丸い View を作成する
個人開発のアプリのテーマカラーの変更画面でよく見かける 色が付いた丸い View の作り方について書いてみたいと思います。
こんなやつ
レイアウト
<?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="wrap_content">
<View
android:id="@+id/color_icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/color_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:text="レッド"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/color_icon"
app:layout_constraintStart_toEndOf="@+id/color_icon"
app:layout_constraintTop_toTopOf="@+id/color_icon"
tools:text="レッド" />
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:background="#cfd8dc"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="@+id/color_name" />
</androidx.constraintlayout.widget.ConstraintLayout>
シェイプドローワブルを作成する
シェイプドローワブル(色やグラデーションなどを含む図形を定義するXMLファイル) を、res/drawable
ディレクトリに作成します。
ファイル名はshape_red_icon.xml
とします。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="15dp" />
<solid android:color="#f44336" />
</shape>
<shape>
タグ
<shape>
タグは、ルート要素でなければいけません。
<corners>
タグ
図形の角を丸くします。
<corners>
タグは四角形にだけ使えますが、上記の実装では図形を指定していません。
なぜなら、<shape>
タグで図形を指定しないときは、デフォルトで四角形のandroid:shape="rectangle"
が適用されるからです。
android:radius
全ての角の半径を指定します。
個別に半径を指定したいときは、android:topLeftRadius
、android:topRightRadius
、android:bottomLeftRadius
、android:bottomRightRadius
を使用します。
<solid>
タグ
図形に使用する単色を指定します。
上記の実装では、android:color="#f44336"
で赤色を設定しています。
Discussion