当然、DialogFragmentもFragmentを継承しているので、この制約を受ける。。
よって、ファイルを分けてpublicクラスでDialogFragmentも定義しなくてはクラッシュすることになる。
しかし、ダイアログなんかは軽く表示させたいし、
わざわざクラスファイルを分けて記述していくのが面倒くさい。。
なので、ファイルを分けなくてすむ方法について記載する。
Fragmentをpublic以外のアクセス修飾子でクラス定義していると、FragmentManagerに追加する際、以下のIllegalStateExceptionが投げられクラッシュする。
Caused by: java.lang.IllegalStateException: Fragment com.sample.test.myapplication.MainActivity.MyDialogFragment must be a public static class to be properly recreated from instance state. at androidx.fragment.app.FragmentTransaction.doAddOp(FragmentTransaction.java:165) at androidx.fragment.app.BackStackRecord.doAddOp(BackStackRecord.java:179) at androidx.fragment.app.FragmentTransaction.add(FragmentTransaction.java:125) at androidx.fragment.app.DialogFragment.show(DialogFragment.java:154) at com.sample.test.myapplication.MainActivity.onClick(MainActivity.java:32)
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>
Androidは公式がGitHubにサンプルプロジェクトを公開している。
これらのサンプルコードを取り込んでビルドしたいときの方法を残しておく。
※GitHubからソースコードを落としたいだけなら、手順2までで良い