【问题标题】:replace fragment with another fragment along with remove view用另一个片段替换片段以及删除视图
【发布时间】:2018-02-21 11:48:42
【问题描述】:

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

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

在我的情况下,显示活动时,显示片段A,当单击按钮时,片段B放置在片段A的底部并且不替换片段A

我的活动代码是:

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;
}
}

【问题讨论】:

    标签: android android-fragments fragment


    【解决方案1】:

    首先,你应该总是在 xml 中有一个 FrameLayout 来替换你的片段,然后你使用 不同的 容器来添加片段 activityFragmentfragmentRoot 。你应该替换片段在一个容器中。您可以将 addreplace 用于 FragmentManager ,因此 activityFragment 是您使用的容器(如文档建议的那样,它应该是一个框架布局作为包装器)

    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();
    }
    

    【讨论】:

    • 并且只需使用 goToFrag onClick 和 FragmentA 中的按钮
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多