Android FragmentManager beginTransaction.add将片段添加到隐藏容器中

时间:2014-01-24 10:35:37

标签: android transactions fragment

有一个MainFragment包含带有id = main_container_layout

的LinearLayout

1.将 fragmentWithTypeA 添加到MainFragment-> LinearLayout

beginTransaction.add(R.id.main_container_layout, fragmentWithTypeA, "555").commit())

fragmentWithTypeA 包含id = container_layout

的LinearLayout

2.一些操作,将someFragment添加到主布局

transaction.hide(fragmentWithTypeA)
    .add(R.id.main_container_layout, someFragment, tag)
    .commit()

3. someFragment中的一些动作

4.创建 anotherFragmentWithTypeA

transaction.hide(someFragment)
    .add(R.id.main_container_layout, anotherFragmentWithTypeA, tag)
    .commit()

5.inside anotherFragmentWithTypeA 我尝试将一些内容添加到LinearLayout

beginTransaction.add(R.id.container_layout, newFragment, "555").commit())

预期结果: newFragment应添加到 anotherFragmentWithTypeA - > LinearLayout

实际结果:newFragment已添加到 fragmentWithTypeA - >在第2步中隐藏了LinearLayout。

1 个答案:

答案 0 :(得分:1)

一种解决方法是在步骤4中创建自定义ID后将自定义ID设置为 anotherFragmentWithTypeA - > LinearLayout。并且在步骤5中将此自定义ID用作容器ID

class FragmentWithTypeA(customContainerId:Int = R.id.container_layout) extends Fragment {
private var _containerLayout : LinearLayout = null

override def onCreateView(inflater:LayoutInflater, container:ViewGroup, savedInstanceState:Bundle ) : View = {
    val view = getActivity.getLayoutInflater.inflate(R.layout.frame_id, null)

    _containerLayout = view.findViewById(R.id.container_layout).asInstanceOf[LinearLayout]
    _containerLayout.setId(customContainerId)

    view
}

}

...

val customContainerId = 7894
val anotherFragmentWithTypeA = new FragmentWithTypeA(customContainerId)

 transaction.hide(someFragment)
.add(R.id.main_container_layout, anotherFragmentWithTypeA, tag)
.commit()

.....

getFragmentManager.beginTransaction.add(customContainerId, newFragment, "111").commit