2021年4月11日日曜日

DialogFragmentは別ファイルに分けないとクラッシュする

前回、Fragmentはpublicクラスで定義しないと落ちる話をした。
当然、DialogFragmentもFragmentを継承しているので、この制約を受ける。。
よって、ファイルを分けてpublicクラスでDialogFragmentも定義しなくてはクラッシュすることになる。

しかし、ダイアログなんかは軽く表示させたいし、
わざわざクラスファイルを分けて記述していくのが面倒くさい。。
なので、ファイルを分けなくてすむ方法について記載する。

FragmentはPublic以外でクラス定義すると落ちる

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)
このエラーが出たときの対処法は、
Fragmentを別のファイルに定義し、publicクラスにすればよい。
本記事では、何故このような制約があるのかについて書いていく。

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>

2021年4月1日木曜日

GitHubで公開されているプロジェクトの取り込み

 Androidは公式がGitHubにサンプルプロジェクトを公開している。

これらのサンプルコードを取り込んでビルドしたいときの方法を残しておく。

※GitHubからソースコードを落としたいだけなら、手順2までで良い