Wiita

自分にとってのメモと, プログラミングに関する情報を発信していきます. サイト名の意味は特にありません.

Androidの画面にMaterialDesignのFloatingButtonを設置する

ただフローティングボタンの置き方を説明します.

Android Developerの公式よりはgithubのほうが情報をみつけやすかったです.

github.com

1. マテリアルデザインのライブラリを追加

まずはマテリアルデザインのライブラリをモジュールのbuild.gradleに追加します.

dependencies {
    // ...
    implementation 'com.google.android.material:material:<version>'
    // ...
  }

バージョンはgithubのreleaseから見れます. 2020年6月3日現在では 1.2.0-beta01 が最新でした. github.com

2. ボタンに表示するアイコンをimport

ご自身の好きなアイコンをimportしてあげても大丈夫ですが, Vector Assetっていう便利なものを使ってみます.

Projectのディレクトリツリーのところ(Android Studioの左側のところw)で右クリックして New => Vector Asset

f:id:ustrgm:20200603235530p:plain
vector asset

こんな画面がでてきます

f:id:ustrgm:20200603235607p:plain
vector asset 設定画面

Clip Artの右側にあるボタンをクリックすると好きなアイコンを選べます.

f:id:ustrgm:20200603235719p:plain
Icon一覧

あとはアイコンを選んで大きさや色, 透明度を設定して Next => import場所を設定してFinishです. import先はデフォルトの main/drawable で今回は進めます.

3. FloatingButtonを設置

設置したいlayoutファイルにxmlを書きます.

 <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end|bottom"
            android:layout_margin="16dp"
            android:contentDescription="@string/fab_content_desc"
            app:srcCompat="@drawable/ic_home" />

上記のは最低限の記述です. 色を変えたりRippleをつけたいと思います. そんなときは公式サイトを見てみると書いてます. material.io

背景色とrippleをつけてみました.

 <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end|bottom"
            android:layout_margin="16dp"
            android:contentDescription="@string/fab_content_desc"
            app:srcCompat="@drawable/ic_home"
            app:backgroundTint="@color/colorPrimary"
            app:rippleColor="@color/primaryLight" />

こんな感じになります

f:id:ustrgm:20200604001845p:plain
終結

ソースコードはこちらにおいてあります. 今後も勉強のために色々実装して更新し続けて行こうと思います. github.com