如何使用导航从其他片段隐藏主机活动中的视图
Posted
技术标签:
【中文标题】如何使用导航从其他片段隐藏主机活动中的视图【英文标题】:How to hide a view in the host activity from other fragment using navigation 【发布时间】:2021-12-22 05:46:51 【问题描述】:activity_main.xml
<androidx.fragment.app.FragmentContainerView
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_
android:layout_
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:defaultNavHost="true"
app:navGraph="@navigation/nav_graph" >
</androidx.fragment.app.FragmentContainerView>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/bottom_controls"
android:layout_
android:layout_
android:onClick="onSongInfoClick"
android:background="@drawable/lyt_rounded_bottom_music"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:elevation="25dp"
app:layout_constraintTop_toBottomOf="@id/nav_host_fragment">
起始目的地是一个由各种选项卡组成的ViewPagerFragment。
当我从 activity_main 中单击 bottom_controls 视图时,我正在导航到 SongDetailsFragment
我不想在 songDetailsFragment
中显示 bottom_controls这是我的尝试:
MainActivity.kt
val currentFragment = supportFragmentManager.currentNavigationFragment
if(currentFragment !== SongDetailsFragment())
viewModel.showMiniPlayer()
else
viewModel.hideMiniPlayer()
SongDetailsFragment.kt
class SongDetailsFragment : BaseSongDetailFragment()
.....
BaseSongDetailFragment.kt
open class BaseSongDetailFragment : Fragment()
private val songDetailViewModel by sharedViewModel<SongDetailViewModel>()
protected val mainViewModel by inject<MainViewModel>()
override fun onActivityCreated(savedInstanceState: Bundle?)
super.onActivityCreated(savedInstanceState)
showHideBottomSheet()
override fun onPause()
showHideBottomSheet()
super.onPause()
override fun onResume()
showHideBottomSheet()
super.onResume()
private fun showHideBottomSheet()
val currentData = songDetailViewModel.currentData.value ?: return
if (currentData.id == 0L) return
val currentFragment =
requireActivity().supportFragmentManager.currentNavigationFragment
if(currentFragment == this as SongDetailsFragment)
mainViewModel.hideMiniPlayer()
else
mainViewModel.showMiniPlayer()
问题:
当我第一次启动应用并导航到 songDetailsFragment 时,它会显示 bottom_controls 视图。
随后,它不显示。
我希望它根本不显示。
【问题讨论】:
【参考方案1】:您可以在活动中使用OnDestinationChangedListener
来监听 currentDestination 的变化。
navController.addOnDestinationChangedListener _, destination, _ ->
if (destination.id == R.id.songDetailsFragment)
viewModel.hideMiniPlayer()
else
viewModel.showMiniPlayer()
【讨论】:
谢谢!!!!!!以上是关于如何使用导航从其他片段隐藏主机活动中的视图的主要内容,如果未能解决你的问题,请参考以下文章