一、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);
}
}