如何解决如何在使用导航时关闭 Android 中的当前片段?
在按钮上设置侦听器后,我创建了 navigationOnClickListener,它将 startDestination 设置为当前片段,在 .navigate() 之后它将目标更改为另一个片段,但视图未更改
onClickListener
navController = Navigation.findNavController(requireActivity(),R.id.nav_host_fragment)
view.findViewById<Button>(R.id.fragment_button).setOnClickListener {
navController.navigate(R.id.Camera2VideoFragment_To_FirstFragment)
}
closeFragment()
private fun closeFragment()
{
closePreviewSession()
closeCamera()
parentFragmentManager.popBackStack()
updatePreview()
}
main.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"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main.xml"
app:startDestination="@id/cameraFragment"
>
<fragment
android:id="@+id/cameraFragment"
android:name="com.example.camera2videotextureview.Camera2VideoFragment"
android:label="Camera2VideoFragment"
tools:layout="@layout/fragment_camera2_video">
<action
android:id="@+id/navigateToSecondFragment"
app:destination="@id/firstFragment" />
</fragment>
<fragment
android:id="@+id/firstFragment"
android:name="com.example.camera2videotextureview.FirstFragment"
android:label="FirstFragment"
tools:layout="@layout/fragment_first" />
</navigation>
主片段是使用 Camera2 API 的相机片段。 FirstFragment 只是一个空白的 kotlin 类,其中布局只包含一个 TextView。
编辑:现在我已经编辑了 onClickListener,我无法更改当前视图,我需要在当前片段上使用 popBackStack,但不知道如何。
解决方法
Navigation.findNavController(mActivity,R.id.nav_host_fragment).popBackStack();
,我解决了我的问题,即我尝试实现了 3 种不同风格的导航。整个导航在过去 4 年中发生了变化,我还发现我将较低 API 与较高 API 的不同版本混合在一起。
我不再使用 closeFragment() 方法。
以下代码声明和代码本身必须在 MainActivity 中实现:
navController = Navigation.findNavController(requireActivity(),R.id.nav_host_fragment)
view.findViewById<Button>(R.id.fragment_button).setOnClickListener {
navController.navigate(R.id.Camera2VideoFragment_To_FirstFragment)
}
您还必须在 xml 文件中为 MainActivity 正确设置 nav_host_fragment:
<androidx.fragment.app.FragmentContainerView
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
app:navGraph="@navigation/main"
/>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。