安卓学习之-Fragment-1

来源:互联网 发布:混沌摆制作方法与数据 编辑:程序博客网 时间:2024/05/29 14:03

在安卓应用中,使用Fragment有两种实现方式:

1.使用XML文件配置

2.使用JavaCode动态填充


一、XML文件

<fragment         android:id="@+id/fragment_center"        android:name="com.demo.fragment01.CenterFragment"        android:layout_weight="2"        android:layout_width="match_parent"        android:layout_height="0dp"/><fragment         android:id="@+id/fragment_buttom"        android:name="com.demo.fragment01.ButtomFragment"        android:layout_weight="1"        android:layout_width="match_parent"        android:layout_height="0dp"/>

 新建两个Fragment类 继承 Fragment,并且重写方法 

        @Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){View view = inflater.inflate(R.layout.fragment_buttom, container,false);return view;}
二、Java代码动态生成

    <FrameLayout        android:id="@+id/layout_center"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="2" />    <FrameLayout        android:id="@+id/layout_buttom"        android:layout_width="match_parent"        android:layout_height="0dp"        android:layout_weight="1" />

  • 在Activity中首先获取FragmentManager
    FragmentManager fragmentManager = getFragmentManager();

  • 通过FragmentManager获取FragmentTransation
    FragmentTransaction transaction = fragmentManager.beginTransaction();

  • 将需要的Fragment实例化 并添加到事务中
    transaction.add(R.id.layout_center,new CenterFragment());transaction.add(R.id.layout_buttom,new ButtomFragment());

  • 将事务提交
    transaction.commit();




0 0
原创粉丝点击