android 在NavGraph的子片段中从活动打开关闭对话框

v64noz0r  于 2023-06-28  发布在  Android
关注(0)|答案(1)|浏览(137)

我想关闭从nav_graph中打开的关于某个事件的对话框。

NavHostActivity.kt xml

<fragment
            android:id="@+id/fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:defaultNavHost="true"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:navGraph="@navigation/nav_graph_settings" />

nav_graph_setting.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nav_graph_settings"
    app:startDestination="@id/settingFragment">

    <fragment
        android:id="@+id/settingFragment"
        android:name="matas.matas.settings.fragment.SettingFragment"
        android:label="Min profil”/>
       
</navigation>

单击SettingFragment中的某个按钮时,调用下面的方法

private fun highLightMemberCard(view: View) {
        childFragmentManager.let {
            val dialog = MemberCardDialogFragment.getInstance(DisplayUtils.dpToPx(requireContext(),65))
            val ft = it.beginTransaction()
            ft.add(dialog, MemberCardDialogFragment.TAG)
            ft.commitAllowingStateLoss()
        }
    }

我只是想在某个事件上关闭Activity中的MemberCardDialogFragment?

qvtsj1bj

qvtsj1bj1#

创建接口

interface CallbackFunction{
    fun closeDialog()
}

在主活动中实现该接口

class MainActivity : AppCompatActivity(),CallbackFunction{
    private lateinit var navController: NavController

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

      val navHostFragment = supportFragmentManager
    .findFragmentById(R.id.nav_host_fragment) as NavHostFragment

       navController = navHostFragment.navController

   }
    override fun closeDialog() {
          navController.popBackStack()
    }

}

在你的片段中调用函数

(activity as MainActivity).closeDialog()

相关问题