Androidの画面にMaterialDesignのFloatingButtonを設置する
ただフローティングボタンの置き方を説明します.
Android Developerの公式よりはgithubのほうが情報をみつけやすかったです.
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
こんな画面がでてきます
Clip Artの右側にあるボタンをクリックすると好きなアイコンを選べます.
あとはアイコンを選んで大きさや色, 透明度を設定して 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" />
こんな感じになります
ソースコードはこちらにおいてあります. 今後も勉強のために色々実装して更新し続けて行こうと思います. github.com