Android開發: fragment解析及案例
Fragment 設計理念
在設計應用時特別是Android 應用 ,有眾多的分辨率要去適應,而fragments 可以讓你在屏幕不同的屏幕上動態管理UI。例如:通訊應用程序(QQ),用戶列表可以在左邊,消息窗口在右邊的設計。而在手機屏幕用戶列表填充屏幕當點擊某一用戶時,則彈出對話窗口的設計,如下圖:
Fragment的生命周期
每一個fragments 都有自己的一套生命周期回調方法和處理自己的用戶輸入事件。 對應生命周期可參考下圖:
其中大多數程序必須使用Fragments 必須實現的三個回調方法分別為:
onCreate
系統創建Fragments 時調用,可做執行初始化工作或者當程序被暫停或停止時用來恢復狀態,跟Activity 中的onCreate相當。
onCreateView
用於首次繪制用戶界面的回調方法,必須返回要創建的Fragments 視圖UI。假如你不希望提供Fragments 用戶界面則可以返回NULL。
onPause
當用戶離開這個Fragments 的時候調用,這時你要提交任何應該持久的變化,因為用戶可能不會回來。更多的事件可以參考上圖的生命周期關系圖
Fragment 的類別
系統內置了三種Fragments ,這三種Fragments 分別有不同的應用場景分別為:
DialogFragment
對話框式的Fragments,可以將一個fragments 對話框並到activity 管理的fragments back stack 中,允許用戶回到一個前曾摒棄fragments.
ListFragments
類似於ListActivity 的效果,並且還提供了ListActivity 類似的onListItemCLick和setListAdapter等功能。
PreferenceFragments
類似於PreferenceActivity .可以創建類似IPAD的設置界面。
Fragment 的詳細使用
首先先來看一張DEMO 效果圖:
左邊點擊時,右邊的字符會與左邊選中的項的字符相同。與IPAD上的設置界面很相似,這一點是否借鑒了ipad 上的UI呢?
相就的XML文件:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="horizontal" >
-
- <fragment class="com.xuzhi.fragment.FragmentDemoActivity$TitlesFragment" android:id="@+id/titles" android:layout_weight="1"
- android:layout_width="0px" android:layout_height="match_parent"
- />
-
- <FrameLayout android:id="@+id/details" android:layout_weight="1" android:layout_width="0px" android:layout_height="match_parent"
- android:background="?android:attr/detailsElementBackground"
- ></FrameLayout>
- </LinearLayout>
主界面代碼(己做注釋):
- package com.xuzhi.fragment;
- import android.app.Activity;
- import android.app.AlertDialog;
- import android.app.Fragment;
- import android.app.FragmentTransaction;
- import android.app.ListFragment;
- import android.os.Bundle;
- import android.util.TypedValue;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
- import android.widget.ScrollView;
- import android.widget.TextView;
-
- public class FragmentDemoActivity extends Activity {
-
- public static String[] array = { "text1,", "text2", "text3", "text4",
- "text5,", "text6", "text7", "text8" };
-
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
-
-
- public static class TitlesFragment extends ListFragment {
-
- boolean mDualPane;
- int mCurCheckPosition = 0;
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- System.out.println("Fragment-->onCreate");
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- System.out.println("Fragment-->onCreateView");
- return super.onCreateView(inflater, container, savedInstanceState);
- }
-
- @Override
- public void onPause() {
- // TODO Auto-generated method stub
- super.onPause();
- System.out.println("Fragment-->onPause");
- }
-
-
- @Override
- public void onStop() {
- // TODO Auto-generated method stub
- super.onStop();
-
- System.out.println("Fragment-->onStop");
- }
-
- @Override
- public void onAttach(Activity activity) {
- // TODO Auto-generated method stub
- super.onAttach(activity);
- System.out.println("Fragment-->onAttach");
- }
-
- @Override
- public void onStart() {
- // TODO Auto-generated method stub
- super.onStart();
- System.out.println("Fragment-->onStart");
- }
-
- @Override
- public void onResume() {
- // TODO Auto-generated method stub
- super.onResume();
- System.out.println("Fragment-->onResume");
- }
-
- @Override
- public void onDestroy() {
- // TODO Auto-generated method stub
- super.onDestroy();
- System.out.println("Fragment-->onDestroy");
- }
-
-
-
- @Override
- public void onActivityCreated(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onActivityCreated(savedInstanceState);
- System.out.println("Fragment-->onActivityCreted");
- setListAdapter(new ArrayAdapter<String>(getActivity(),
- android.R.layout.simple_list_item_1, array));
-
- View detailsFrame = getActivity().findViewById(R.id.details);
-
- mDualPane = detailsFrame != null
- && detailsFrame.getVisibility() == View.VISIBLE;
-
- if (savedInstanceState != null) {
- mCurCheckPosition = savedInstanceState.getInt("curChoice", 0); //從保存的狀態中取出數據
- }
-
- if (mDualPane) {
- getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
-
- showDetails(mCurCheckPosition);
- }
- }
-
- @Override
- public void onSaveInstanceState(Bundle outState) {
- // TODO Auto-generated method stub
- super.onSaveInstanceState(outState);
-
- outState.putInt("curChoice", mCurCheckPosition);//保存當前的下標
- }
-
- @Override
- public void onListItemClick(ListView l, View v, int position, long id) {
- // TODO Auto-generated method stub
- super.onListItemClick(l, v, position, id);
- showDetails(position);
- }
-
- void showDetails(int index) {
- mCurCheckPosition = index;
- if (mDualPane) {
- getListView().setItemChecked(index, true);
- DetailsFragment details = (DetailsFragment) getFragmentManager()
- .findFragmentById(R.id.details);
- if (details == null || details.getShownIndex() != index) {
- details = DetailsFragment.newInstance(mCurCheckPosition);
-
- //得到一個fragment 事務(類似sqlite的操作)
- FragmentTransaction ft = getFragmentManager()
- .beginTransaction();
- ft.replace(R.id.details, details);//將得到的fragment 替換當前的viewGroup內容,add則不替換會依次累加
- ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);//設置動畫效果
- ft.commit();//提交
- }
- } else {
- new AlertDialog.Builder(getActivity()).setTitle(
- android.R.string.dialog_alert_title).setMessage(
- array[index]).setPositiveButton(android.R.string.ok,
- null).show();
- }
- }
- }
-
- /**
- * 作為界面的一部分,為fragment 提供一個layout
- * @author terry
- *
- */
- public static class DetailsFragment extends Fragment {
-
- public static DetailsFragment newInstance(int index) {
- DetailsFragment details = new DetailsFragment();
- Bundle args = new Bundle();
- args.putInt("index", index);
- details.setArguments(args);
- return details;
- }
-
- public int getShownIndex() {
- return getArguments().getInt("index", 0);
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- if (container == null)
- return null;
-
- ScrollView scroller = new ScrollView(getActivity());
- TextView text = new TextView(getActivity());
-
- int padding = (int) TypedValue.applyDimension(
- TypedValue.COMPLEX_UNIT_DIP, 4, getActivity()
- .getResources().getDisplayMetrics());
- text.setPadding(padding, padding, padding, padding);
- scroller.addView(text);
-
- text.setText(array[getShownIndex()]);
- return scroller;
- }
- }
- }
-
注意:
- 如果你想在Fragment 裡面創建menu,則必須在onCreate的時候設置讓它可以存在optionMenu才可以創建,代碼為:
- public static class DetailsFragment extends Fragment {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- super.onCreate(savedInstanceState);
- setHasOptionsMenu(true);
- }
- }
之後的操作即可以像平常Android的menu用法一樣,代碼為:
- @Override
- public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
- // TODO Auto-generated method stub
- super.onCreateOptionsMenu(menu, inflater);
- menu.add("Menu 1a").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
- menu.add("Menu 1b").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- // TODO Auto-generated method stub
- Toast.makeText(getActivity(), "index is"+getShownIndex()+" && menu text is "+item.getTitle(), 1000).show();
- return super.onOptionsItemSelected(item);
- }