AndroidアプリでButtonの上にViewやFragmentを乗せても、
Buttonが表示物に隠れず、ボタンが上に重なって表示される。
解決方法として、ボタンの属性「stateListAnimator」に「"@null"」を設定すれば良い。
例えば、ボタンの上に画像(ImageView)を配置したいときは以下のようにする。
- <?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="match_parent"
- tools:context=".MainActivity">
- <Button
- android:id="@+id/button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent"
- android:stateListAnimator="@null" ★ コレ! ★
- />
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher_background"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent"
- />
- </androidx.constraintlayout.widget.ConstraintLayout>
以降で、Viewの「重なり」はどうなっているのか?について解説する。
ViewのZ軸(z-index)について
Viewが重なるとき、どちらのViewが上に乗るのか。はViewのZ軸によって決まる。
Z軸を決め方は
静的(レイアウトxml)の場合、上から順番に重なる為、下の行に書いたViewが上に乗る。
Z軸を決め方は
静的(レイアウトxml)の場合、上から順番に重なる為、下の行に書いたViewが上に乗る。
動的(ソース制御)の場合、ViewGroupにAddした順番で重なる為、後から追加したViewが上に乗る。
上で書いたサンプルコードを例にすると、ボタンの上に画像を乗せたいので<ボタン><画像>の順番で記述しているわけである。
マテリアルデザインの影(Viewの高低)の概念
Android5.0からマテリアルデザインが導入された。
よって、ViewはZ軸を超えて浮くようになり、Viewの上に重なるようになった。
ちなみにButtonはデフォルトで「1dp」浮いている。
対処するには、重ねたいViewも浮かせるか、ボタンの浮きを消すか。
今回の解決策は、ボタンの浮きを消す方法を取っているので、
「ボタンの属性「stateListAnimator」に「"@null"」を設定する」としている。
0 件のコメント:
コメントを投稿