【问题标题】:How to get fragments from backstack when using Android Navigation Component?使用Android导航组件时如何从后台获取片段?
【发布时间】:2021-11-01 09:25:38
【问题描述】:

在使用 Android 导航组件时,如何访问 backstack 中的任何片段? 让我们使用导航组件导航到片段 A,然后导航到片段 B,然后导航到片段 C。 现在您要访问 Fragment A 或 Fragment B 实例(不弹出任何片段)并将值设置为其字段之一。 过去,我们可以使用 findFragmentByTag 来做到这一点。 但是现在使用导航组件怎么办呢?

【问题讨论】:

  • 这根本不是你应该的communicating with fragments。文档中的所有技术都适用于导航组件。
  • @ianhanniballake 感谢您的评论,包括链接。我相信我以前读过这个,但他们每天都在改变文件!我学到了一些新东西。再次感谢!

标签: android kotlin android-fragments navigation fragment-backstack


【解决方案1】:

如果您想访问同一活动中的其他片段数据,使用SharedViewModel 可能是个好主意。您可以查看SharedViewModel 示例。

class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<Item>()

    fun select(item: Item) {
        selected.value = item
    }
}

class ListFragment : Fragment() {

    private lateinit var itemSelector: Selector

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        itemSelector.setOnClickListener { item ->
            // Update the UI
        }
    }
}

class DetailFragment : Fragment() {

    // Use the 'by activityViewModels()' Kotlin property delegate
    // from the fragment-ktx artifact
    private val model: SharedViewModel by activityViewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
            // Update the UI
        })
    }
}

如果您想查看更多详细信息,这里是official documentationSharedViewModel

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多