首页 > 解决方案 > 如何以编程方式将片段添加到 kotlin 中的片段

问题描述

我有一个片段,它实际上是我的应用程序中的一个屏幕......在这个屏幕上,我想根据传递给屏幕片段的模型的属性加载多个片段之一。我将使用条件 when... 但首先:

我什至无法加载基本片段。这是屏幕片段的代码:

类EditCommandFragment:片段(){

private val args by navArgs<EditCommandFragmentArgs>()
private lateinit var fragContainer: ConstraintLayout

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    setHasOptionsMenu(true)

    // Inflate the layout for this fragment
    val view = inflater.inflate(R.layout.fragment_edit_command, container, false)
    //get a reference to the container.
    fragContainer = view.findViewById<ConstraintLayout>(R.id.command_edit_container)
    
    // add one of the edit fragments //this doesn't work
    childFragmentManager.beginTransaction().add(fragContainer, EditCommandUIFragment.newInstance()).commit()

    return view
}

抛出的这个错误是:

不能使用提供的参数调用以下函数:

public open fun add(p0: Fragment, p1: String?): FragmentTransaction defined in androidx.fragment.app.FragmentTransaction
public open fun add(p0: Int, p1: Fragment): FragmentTransaction defined in androidx.fragment.app.FragmentTransaction

但这没有任何意义。在所有教程中,我可以找到您将容器作为 p0 传递,然后将要添加的片段的类作为 p1 传递......但这是要求一个字符串或一个 int,什么?

如何正确地将我的 EditCommandUIFragment 添加到容器中?

标签: androidkotlin

解决方案


要添加片段,您需要片段的实例,而不是它的“视图”(这是片段的管理责任)。

  1. 使用“推荐方法”构造您的“子”片段的实例:
val yourNewFragment = YourNewFragment.newInstance()
  1. 获取您将放置此的容器...
val container = R.id.place_where_you_will_put_it
  1. 执行交易:
childFragmentManager.beginTransaction().add(container, yourNewFragment, "A TAG or NULL")

现在,请记住,如果您确实使用了标签,那么检查片段是否已经存在有时是一种很好的做法(这实际上取决于您的应用程序/生命周期/等)...

val frag = childFragmentManager.findFragmentByTag("The Tag You Used Above")

if (frag == null) { 
   // add it
}

你明白了。

如果您不使用 TAG”,那么您可以使用其他替代方案...

val frag = childFragmentManager.findFragmentById(id of the container where the fragment is supposed to be, aka: R.id.place_where_you_will_put_it)

例如,这可以用于replace(...)片段,而不是add.


推荐阅读