第一步:新建一个left_fragment布局
第二步:新建一个right_fragment布局
第三步:新建一个LeftFragment类,并继承自Fragment
public class LeftFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.left_fragment,container,false); return view; } }
第四步:新建一个RightFragment类,并继承自Fragment
public class RightFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.right_fragment,container,false); return view; } }
第五步:修改activity_main的代码
动态添加:
第一步:新建所需的另一个界面another_right_fragment(设置了一个文本)
第二步:创建一个AnotherRightFragment类(加载创建的布局)
public class AnotherRightFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.another_right_fragment,container,false); return view; } 第三步:修改activity_main布局
第四步:修改MainActivity中的内容
1、注册点击事件
2、replaceFragment方法()
(1)创建待添加的实例
(2)获取FragmentManager,在活动中直接调用getSupportFragmentManager()得到。
FragmentManager fragmentManager=getSupportFragmentManager();
(3)开启一个事务,通过beginTransaction()开启。
FragmentTransaction transaction = fragmentManager.beginTransaction();
(4)向容器内添加或替换碎片,使用replace()方法完成
transaction.replace(R.id.right_layout,fragment);
(5)提交事务,调用commit()方法完成
transaction.commit();
(2)(3)(4)(5)总体代码:
在碎片中返回模拟栈
碎片与活动之间的通信
1、在活动中得到相应碎片
RightFragment rightFragment = getSupportFragmentManager().findFragmentById(R.id.right_fragment);
2、在碎片中得到活动
MainActivity activity = (MainActivity) getActivity();
碎片的状态
1、运行状态
2、暂停状态
3、停止状态
4、销毁状态
动态加载
一、使用限定符(自动判断使用双页/单页模式)
第一步:修改activity_main文件
删除多余代码,只留下左侧碎片,并使其充满整个父布局
第二步:在res目录下新建layout-large文件夹,在其下面新建一个布局,叫做activity_main.xml
二、使用最小宽度限定符
第一步:与上述一样
第二步:在res目录下新建layout-sw600dp文件夹,在其下面新建一个布局,叫做activity_main.xml