我今天刚学习片段。我按下一个按钮,它会添加/删除一个片段。但是,如果我尝试删除片段,除了我要删除的片段之外的每个片段都会被删除,为什么?第一次正确添加片段。
Button2 fragment:
Button button = (Button) view.findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ButtonFragment fragment = new ButtonFragment();
if (fragment != null && fragment.isVisible()) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.remove(fragment).commit();
}
else if(!fragment.isVisible())
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.fragment_container, fragment ).commit();
}
}
});
return view;
}
}
我在xml中有两个这样的片段: 当我单击按钮时,我想要添加未在xml中定义的片段,它就是。 但是,下次按下按钮时,应删除该片段。除了那个片段之外,一切都被删除了。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:background="#123456"
android:id="@+id/fragment_container" >
<fragment
android:id="@+id/TimeFragment"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="match_parent"
class="com.example.myfragment.TimeFragment" >
<!-- Preview: layout=@layout/details -->
</fragment>
<fragment
android:id="@+id/Button2Fragment"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="match_parent"
class="com.example.myfragment.Button2Fragment" >
<!-- Preview: layout=@layout/details -->
</fragment>
</LinearLayout>
答案 0 :(得分:2)
您无法删除使用XML添加的Framgnet
。如果要通过.remove
方法删除片段,首先应通过.add
方法将其添加到布局中,而不是将其嵌入到XML文件中。在这种情况下,您只能.show
或.hide
Fragments
。
<强>更新强>
要动态添加ButtonFragment
,请执行以下操作:
ButtonFragment buttonsFragment = new ButtonFragment();
newfragmentTransaction = fragmentManager.beginTransaction();
newfragmentTransaction.add(R.id.containerForFragments, buttonsFragment ).commit();
更新2: 这段代码:
Button button = (Button) view.findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ButtonFragment fragment = new ButtonFragment();
if (fragment != null && fragment.isVisible()) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.remove(fragmentManager.findFragmentById(R.layout.activity_main)).commit();
}
else if(!fragment.isVisible())
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.layout.activity_main, fragment ).commit();
}
}
});
应该从Activity
开始,而不是从Fragment
开始。