LoginSignup
0
0

More than 3 years have passed since last update.

色が付いた丸いViewを作成する

Posted at

テーマカラーの変更画面でよく見かける「色が付いた丸いView」の作り方です。

※レイアウトイメージ(テキストと区切り線はおまけです)
Screenshot_1615552027.png

レイアウト(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="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とします。

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:topLeftRadiusandroid:topRightRadiusandroid:bottomLeftRadiusandroid:bottomRightRadiusを使用します。

<solid>タグ

図形に使用する単色を指定します。

上記の実装では、android:color="#f44336"で赤色を設定しています。

まとめ

これで色が付いた丸いViewを作ることが出来ると思います。

次回は、今回の実装を含めて「テーマカラーを変更するアプリ」を作ってみたいと思います。

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