动态添加Fragment步骤

1.创建一个类继承Fragment,复写onCreateView方法。
例如:

public class AnotherRightFragment extends Fragment{  

  @Override 
  public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){  

  //传进fragment布局文件创建一个view对象 
  View view =inflater.inflate(R.layout_another_right_fragment,container,flase);
  return view; 
  }
}

2.在MainActivity中创建待添加的fragment实例。

AnotherRightFragment fragment = new AnotherRightFragment();

3.在Activity中通过调用个体FragmentManager()方法获取到FragmentManager。

FragmentManager fragmentManager = getFragmentManager();

4.开启一个事物,通过调用beginTransaction()方法开启。

FragmentTransaction transaction = fragmentManager.beginTransaction();

5.向容器内加入Fragment,一般使用replace()方法实现,需要传入容器的id和待添加的碎片实例。

transaction.replace(R.id.right_layout,fragment);

6.提交事务,调用commit()方法来完成。

transaction.commit();

在Fragment中模拟返回栈 transaction.addToBackStack(null);
(该方法对使用support.v4.fragment兼容包有效,对使用android.app包还未找到对应方法)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容