一、Fragment的简介
1.Fragment是Android honeycomb 3.0新增的概念,你可以将Fragment类比为Activity的一部分
2. 拥有自己的生命周期,接收自己的输入,你可以在Activity运行的时加入或者移除Fragment
3. 碎片必须位于是视图容器
二、Fragment的生命
setContentView ---- onInflate
create ---- onAttach: 碎片与其活动关联 (getActitvity():返回碎片附加到的活动)
create ---- onCreate: 不能放活动视图层次结构的代码
create ---- onCreateView: 返回碎片的视图层次结构
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (null == container) //容器父元素
{
return null;
}
View v = inflater.iniflate(R.layout.details, container, false);
TextView textview = (TextView)v.findViewById(R.id.textview).
textview.setText("");
return v;
}
LayoutInflater类,它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化;
而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)。
具体作用:
1、对于一个没有被载入或者想要动态载入的界面,都需要使用LayoutInflater.inflate()来载入;
2、对于一个已经载入的界面,就可以使用Activiyt.findViewById()方法来获得其中的界面元素。
create ---- onActivityCreated: 活动的onCreate之后调用,用户还未看到界面
start ---- onStart: 用户能看到碎片
resume ---- onResume: 调用之后,用户可以与用于程序调用
pause ---- onPause: 可暂停,停止或者后退
---- onSaveInstanceState:保存对象
stop ---- onStop
destory ---- onDestroyView:
destory ---- onDestroy
destory ---- onDetach: 碎片与活动解绑
---- setRetainInstance: 如果参数为true,表明希望将碎片对象保存在内存中,而不从头创建
三、 Fragment关键代码示例
1. 使用静态工厂方法实例化碎片
public static MyFragment newInstance(int index) {
MyFragment f = new MyFragment();
Bundle args =new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
2. 获取是否多窗口的函数
public boolean isMultiPane() {
return gerResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
}
3. FragmentTransaction用于实现交互
FragmentTransactin ft = getFragmentManager().beginTransaction();
ft.setTranstition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//ft.addToBackStack("details"); //如果碎片使用后退栈,需要使用该函数
ft.replace(R.id.details, details);
ft.commit();
4.
ObjectAnimator自定义动画
FragmentTransaction类中指定自定义动画的唯一方法是setCustomAnimations()
从左滑入的自定义动画生成器
<?xml version="1.0", encoding="utf-8"?>
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:interpolator/accelerate_decelerate" //插值器在android.R.interpolator中列出
android:valueFrom="-1280"
android:valueTo="0" //动画完成时,可以让用户看到
android:valueType="floatType"
android:propertyNmae="x" // 动画沿那个维度发生
android:duration="2000" />
<set>可以封装多个<objectAnimator>
5. fragment如何跳转到其他activity
示例代码:(特别注意:MallActivity需要在AndroidManifest.xml中声明)
public class MallFragment extends Fragment {
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// 这个方法你可以获取到父Activity的引用。
Intent intent = new Intent(getActivity(), MallActivity.class);
startActivity(intent);
}
}