用另一个片段替换片段以及删除视图

时间:2018-02-21 11:48:42

标签: android android-fragments fragment

我有一个活动和两个碎片。 FragmentA和FragmentB。

我需要实现像,最初FragmentA应该在那里。 在Button点击FragmentB后应该在那里。

在我的情况下显示活动时,片段A显示,当点击按钮时,fragmentB放在fragmentA的底部,不要替换FragmentA

我的活动代码是:

public class FragmentActivity extends AppCompatActivity {

FrameLayout activityFragment;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fragment);
    activityFragment = (FrameLayout) findViewById(R.id.activityFragment);
    Fragment fragment = new FragmentA();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.activityFragment, fragment);
    transaction.commit();
}

public void goToFrag(View view) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    Fragment fragment = new FragmentB();
    transaction.add(R.id.fragmentRoot, fragment);
    transaction.commit();
}
}

我的第一个片段代码:

  public class FragmentA extends Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view=inflater.inflate(R.layout.fragment_a,container,false);
    return view;
}
}

我的第二个片段代码:

   public class FragmentB extends Fragment {
public FragmentB() {
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
     super.onCreateView(inflater, container, savedInstanceState);
    View view=inflater.inflate(R.layout.fragment_b,container,false);
    return view;
}
}

2 个答案:

答案 0 :(得分:0)

在您的Activity中,编写以下方法,然后在单击按钮时调用此方法。

public void replaceFrag() {
   FragmentB fragment = new FragmentB();
   getSupportFragmentManager().beginTransaction()
                              .replace(R.id.fragmentRoot, fragment)
                              .addToBackStack(null)
                              .commit();
}

答案 1 :(得分:0)

首先,您应该始终在xml中使用FrameLayout来替换那里的片段,然后使用不同的容器添加片段activityFragment和{{1}你应该在一个容器中替换片段。您可以fragmentRoot使用addreplace FragmentManager,因此activityFragment是您的容器(应该是一个framelayout作为文档建议的包装器)您使用

public void goToFrag(View view) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    Fragment fragment = new FragmentB();
    transaction.replace(R.id.activityFragment, fragment); // use the same container where you switch A and B
    transaction.commit();
}
相关问题