Fagment :为了让程序更加合理和充分的利用大屏幕的空间,而嵌入在活动当中的UI片段
一、Fragment的基本用法
新建Java类继承自Fragment,重写onCreateView()方法加载fragment的布局,代码如下:
public class MyFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_xxx,container,false);
return view;
}
}
在Activity的布局中引用的时候在xml文件中加fragment标签即可,
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/left_fragment"
android:name="com.example.administrator.mycontext.MyFragment"
android:layout_weight="1"/>
<fragment
android:layout_width="0dp"
android:layout_height="match_parent"
android:id="@+id/right_fragment"
android:name="com.example.administrator.mycontext.MyFragment"
android:layout_weight="1"/>
</LinearLayout>
二、Fragment的动态添加
(1)创建待添加的碎片实例,(2)获取FragmentManager,在活动中可以直接通过调用getSupportFragmentManager()方法得到(3)开启一个事务,(4)替换调用replace()方法,(5)提交事务
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.layout,fragment);
fragmentTransaction.addToBackStack(null)//模拟返回栈
fragmentTransaction.commit();
}
同时也需要将活动的布局文件中的待替换的<fragment>标签换成<FrameLayout>
三、Fragment和活动之间通信
在活动中得到Fragment的实例
OneFragment onfragment=(OneFragment)getSupportFragmentManager().findFragmentById(R.id.xxx);
在Fragment中得到活动的实例
MainActivity activity=(MainActivity)getActivity();
四、Fragment的生命周期
运行态:表示碎片是可见的
暂停态:活动进入暂停时,跟它关联的碎片也进入暂停态
停止态:活动进入停止态时,跟它相关联的碎片也进入停止态
销毁态:活动被销毁时,跟它相关联的碎片也进入销毁态
生命周期示意图