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)を配置したいときは以下のようにする。

<?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>

2021年4月1日木曜日

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

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

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

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