💬

[Android][kotlin]疑似BottomSheetDialogFragmentのサンプル

に公開

Abstract

  • Androidで疑似BottomSheetDialogFragmentを作ったのでそのサンプル
  • その説明

概要

疑似BottomSheetDialogFragmentをつくった動機なんだけど。
Androidには共有要素遷移ってカッコいい機能があるのでそれを、普通のFragment → BottomSheetDialogFragment間で実行してみたかったんだけど、仕様上無理でしたー。

ならば、通常Fragment を BottomSheetDialogFragmentっぽく作ったら、イケるんじゃね。と思ったのがモチベーションです。

という事でソースコードをgithubに公開しました。
https://github.com/aaaa1597/AndKot-MimicBottomSheetFragmentSample.git

使い方

上記githubからcloneなりzipダウンロードして、Android Studioで開くだけ。

実装のポイント

分かってしまえば簡単。

  • Navigationコンポーネントは使わない。
  • DialogFragmentを使っていないので、共有要素遷移が追加可能。(たぶん)
  • parentFragmentManager.beginTransaction().add()にアニメーションを加えて“下から出る”動作を再現。
    -呼び先Fragmentのxmlにも、透過設定。

使ってたらFragment重ねができません。

DialogFragmentを使っていないので、共有要素遷移が追加可能。(たぶん)

たぶん。。。

parentFragmentManager.beginTransaction().add()にアニメーションを加えて“下から出る”動作を再現。

FragmentA.kt
            parentFragmentManager.beginTransaction()
                .setCustomAnimations(R.anim.nav_up_enter_anim, R.anim.nav_up_exit_anim)
                .setReorderingAllowed(true)
                .add(R.id.fragment_container, MimicBottomSheetFragment::class.java, null, "MimicBottomSheetFragment")
//              ↑★★ココ
                .addToBackStack(null)
                .commit()

呼び先Fragmentのxmlにも、透過設定。

fragment_mimic_bottom_sheet.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/backgroundView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="24dp"
    android:background="@android:color/transparent"  ←★★ココ
    tools:context=".MimicBottomSheetFragment">

よし、次は共通要素遷移だ!!

以上、疑似BottomSheetDialogFragmentの説明でした。
お役に立ちますように。。。

Discussion