Loading [MathJax]/extensions/tex2jax.js

2021年4月10日土曜日

Buttonの上にViewを載せる

AndroidアプリでButtonの上にViewやFragmentを乗せても、

Buttonが表示物に隠れず、ボタンが上に重なって表示される。

解決方法として、ボタンの属性「stateListAnimator」に「"@null"」を設定すれば良い。

例えば、ボタンの上に画像(ImageView)を配置したいときは以下のようにする。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.constraintlayout.widget.ConstraintLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. xmlns:app="http://schemas.android.com/apk/res-auto"
  5. xmlns:tools="http://schemas.android.com/tools"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. tools:context=".MainActivity">
  9.  
  10. <Button
  11. android:id="@+id/button"
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="Button"
  15. app:layout_constraintBottom_toBottomOf="parent"
  16. app:layout_constraintEnd_toEndOf="parent"
  17. app:layout_constraintStart_toStartOf="parent"
  18. app:layout_constraintTop_toTopOf="parent"
  19. android:stateListAnimator="@null" ★ コレ! ★
  20. />
  21. <ImageView
  22. android:layout_width="wrap_content"
  23. android:layout_height="wrap_content"
  24. android:src="@drawable/ic_launcher_background"
  25. app:layout_constraintBottom_toBottomOf="parent"
  26. app:layout_constraintEnd_toEndOf="parent"
  27. app:layout_constraintStart_toStartOf="parent"
  28. app:layout_constraintTop_toTopOf="parent"
  29. />
  30.  
  31. </androidx.constraintlayout.widget.ConstraintLayout>


以降で、Viewの「重なり」はどうなっているのか?について解説する。


ViewのZ軸(z-index)について

Viewが重なるとき、どちらのViewが上に乗るのか。はViewのZ軸によって決まる。
Z軸を決め方は
静的(レイアウトxml)の場合、上から順番に重なる為、下の行に書いたViewが上に乗る。
動的(ソース制御)の場合、ViewGroupにAddした順番で重なる為、後から追加したViewが上に乗る。

上で書いたサンプルコードを例にすると、ボタンの上に画像を乗せたいので
<ボタン>
<画像>
の順番で記述しているわけである。



マテリアルデザインの影(Viewの高低)の概念

Android5.0からマテリアルデザインが導入された。
これにより、Viewに影をつけるデザインが使われるようになり、Buttonも標準で影がついている。
よく見ると、ボタンの下に影があるのがわかる


よって、ViewはZ軸を超えて浮くようになり、Viewの上に重なるようになった。
ちなみにButtonはデフォルトで「1dp」浮いている。
対処するには、重ねたいViewも浮かせるか、ボタンの浮きを消すか。
今回の解決策は、ボタンの浮きを消す方法を取っているので、
「ボタンの属性「stateListAnimator」に「"@null"」を設定する」としている。

0 件のコメント:

コメントを投稿