Android類參考---Fragment(一)


1. 繼承關系

java.lang.Object

|__android.app.Fragment

實現接口:ComponentCallbacks2 View.OnCreateContextMenuListener

引入版本:API Level 11

已知的子類:

DialogFragment、ListFragment、PreferenceFragment、WebViewFragment

2. 類概要

一個Fragment是應用程序的用戶界面或行為的一個片段,它能夠被放置在一個Activity中。通過FragmentManager對象來實現與Fragment對象的交互,能夠通過Activity.getFragmentManager()方法和Fragment.getFragmentManager()方法來獲取FragmentManager對象。

Fragment類有着廣泛的應用,它的核心是代表了一個正在較大的Activity中運行的特俗的操作或界面。Fragment對象跟它所依附的Activity對象是緊密相關的,並且不能被分開使用。盡管Fragment對象定義了它們自己的生命周期,但是這個生命周期要依賴與它所在的Activity:如果該Activity被終止,那么它內部的Fragment是不能被啟動的;當Activity被銷毀時,它內部的所有Fragment對象都會被銷毀。

所有的Fragment子類都必須包含一個公共的空的構造器。在需要的時候,Framework會經常重新實例化Fragment類,在特殊的狀態恢復期間,需要能夠找到這個構造器來實例化Fragment類。如果空的構造器無效,那么在狀態恢復期間會導致運行時異常發生。

較舊的平台

盡管Fragment API是在HONEYCOMB版本中被引入的,但是通過FragmentActivity也能夠在較舊的平台上使用該API。

聲明周期

盡管Fragment對象的生命周期要依附於它所在的Activity對象,但是它也有自己標准的活動周期,它包含了基本的活動周期方法,如onResume(),但是同時也包含了與Activity和UI交互相關的重要方法。

顯示Fragment時(跟用戶交互)要調用的核心的生命周期方法如下:

1. 把Fragment對象跟Activity關聯時,調用onAttach(Activity)方法;

2. Fragment對象的初始創建時,調用onCreate(Bundle)方法;

3. onCreateView(LayoutInflater, ViewGroup, Bundle)方法用於創建和返回跟Fragment關聯的View對象;

4. onActivityCreate(Bundle)方法會告訴Fragment對象,它所依附的Activity對象已經完成了Activity.onCreate()方法的執行;

5. onStart()方法會讓Fragment對象顯示給用戶(在包含該Fragment對象的Activity被啟動后);

6. onResume()會讓Fragment對象跟用戶交互(在包含該Fragment對象的Activity被啟恢復后)。

Fragment對象不再使用時,要反向回調的方法:

1. 因為Fragment對象所依附的Activity對象被掛起,或者在Activity中正在執行一個修改Fragment對象的操作,而導致Fragment對象不再跟用戶交互時,系統會調用Fragment對象的onPause()方法;

2. 因為Fragment對象所依附的Activity對象被終止,或者再Activity中正在執行一個修改Fragment對象的操作,而導致Fragment對象不再顯示給用戶時,系統會調用Fragment對象的onStop()方法。

3. onDestroyView()方法用於清除跟Fragment中的View對象關聯的資源;

4. Fragment對象的狀態被最終清理完成之后,要調用onDestroy()方法;

5. 在Fragment對象不再跟它依附的Activity關聯的時候,onDetach()方法會立即被調用。

 

布局

Fragment對象能夠被用於應用程序的布局,它會讓代碼的模塊化更好,並且針對Fragment所運行的屏幕,讓用戶界面的調整更加容易。例如,一個簡單的由項目列表和項目明細表示所組成的程序。

一個Activity的布局XML能夠包含要嵌入到布局內部的Fragment實例的<fragment>標簽。例如,下例中在布局中嵌入了一個Fragment對象:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:layout_width="match_parent" android:layout_height="match_parent">
   
<fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"
           
android:id="@+id/titles"
           
android:layout_width="match_parent" android:layout_height="match_parent" />
</FrameLayout>

以下是布局被安裝到Activity中的通常方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
   
super.onCreate(savedInstanceState);

    setContentView
(R.layout.fragment_layout);
}

依賴ListFragment對象,要顯示列表的標題是相當簡單的。要注意的是,點擊一個列表項的實現,會依賴當前Activity的布局,它既可以創建一個新的Fragment用於顯示該項目的明細,也可以啟動一個新的Activity用於顯示項目的明細。

public static class TitlesFragment extends ListFragment {
   
boolean mDualPane;
   
int mCurCheckPosition = 0;

   
@Override
   
public void onActivityCreated(Bundle savedInstanceState) {
       
super.onActivityCreated(savedInstanceState);

       
// Populate list with our static array of titles.
        setListAdapter
(new ArrayAdapter<String>(getActivity(),
                android
.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));

       
// Check to see if we have a frame in which to embed the details
       
// fragment directly in the containing UI.
       
View detailsFrame = getActivity().findViewById(R.id.details);
        mDualPane
= detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

       
if (savedInstanceState != null) {
           
// Restore last state for checked position.
            mCurCheckPosition
= savedInstanceState.getInt("curChoice", 0);
       
}

       
if (mDualPane) {
           
// In dual-pane mode, the list view highlights the selected item.
            getListView
().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
           
// Make sure our UI is in the correct state.
            showDetails
(mCurCheckPosition);
       
}
   
}

   
@Override
   
public void onSaveInstanceState(Bundle outState) {
       
super.onSaveInstanceState(outState);
        outState
.putInt("curChoice", mCurCheckPosition);
   
}

   
@Override
   
public void onListItemClick(ListView l, View v, int position, long id) {
        showDetails
(position);
   
}

   
/**
     * Helper function to show the details of a selected item, either by

     * displaying a fragment in-place in the current UI, or starting a
     * whole new activity in which it is displayed.
     */

   
void showDetails(int index) {
        mCurCheckPosition
= index;

       
if (mDualPane) {
           
// We can display everything in-place with fragments, so update
           
// the list to highlight the selected item and show the data.
            getListView
().setItemChecked(index, true);

           
// Check what fragment is currently shown, replace if needed.
           
DetailsFragment details = (DetailsFragment)
                    getFragmentManager
().findFragmentById(R.id.details);
           
if (details == null || details.getShownIndex() != index) {
               
// Make new fragment to show this selection.
                details
= DetailsFragment.newInstance(index);

               
// Execute a transaction, replacing any existing fragment
               
// with this one inside the frame.
               
FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft
.replace(R.id.details, details);
                ft
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft
.commit();
           
}

       
} else {
           
// Otherwise we need to launch a new activity to display
           
// the dialog fragment with selected text.
           
Intent intent = new Intent();
            intent
.setClass(getActivity(), DetailsActivity.class);
            intent
.putExtra("index", index);
            startActivity
(intent);
       
}
   
}
}

明細Fragment對象只會顯示所選項目的詳細文本字符串,它是基於內置在應用中的一個字符數組的索引來獲取的:

public static class DetailsFragment extends Fragment {
   
/**
     * Create a new instance of DetailsFragment, initialized to

     * show the text at 'index'.
     */

   
public static DetailsFragment newInstance(int index) {
       
DetailsFragment f = new DetailsFragment();

       
// Supply index input as an argument.
       
Bundle args = new Bundle();
        args
.putInt("index", index);
        f
.setArguments(args);

       
return f;
   
}

   
public int getShownIndex() {
       
return getArguments().getInt("index", 0);
   
}

   
@Override
   
public View onCreateView(LayoutInflater inflater, ViewGroup container,
           
Bundle savedInstanceState) {
       
if (container == null) {
           
// We have different layouts, and in one of them this
           
// fragment's containing frame doesn't exist.  The fragment
           
// may still be created from its saved state, but there is
           
// no reason to try to create its view hierarchy because it
           
// won't be displayed.  Note this is not needed -- we could
           
// just run the code below, where we would create and return
           
// the view hierarchy; it would just never be used.
           
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(Shakespeare.DIALOGUE[getShownIndex()]);
       
return scroller;
   
}
}

在用戶點擊標題的情況下,在當前的Activity中沒有明細容器,因此標題Fragment的點擊事件代碼會啟動一個新的顯示明細Fragment的Activity:

public static class DetailsActivity extends Activity {

   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);

       
if (getResources().getConfiguration().orientation
               
== Configuration.ORIENTATION_LANDSCAPE) {
           
// If the screen is now in landscape mode, we can show the
           
// dialog in-line with the list so we don't need this activity.
            finish
();
           
return;
       
}

       
if (savedInstanceState == null) {
           
// During initial setup, plug in the details fragment.
           
DetailsFragment details = new DetailsFragment();
            details
.setArguments(getIntent().getExtras());
            getFragmentManager
().beginTransaction().add(android.R.id.content, details).commit();
       
}
   
}
}

但是,屏幕可能足夠顯示標題列表和當前所選標題相關的明細。對於在橫向屏幕上這樣的布局,可以被放置在layout-land下面:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   
android:orientation="horizontal"
   
android:layout_width="match_parent" android:layout_height="match_parent">

   
<fragment class="com.example.android.apis.app.FragmentLayout$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" />

</LinearLayout>

要注意的是,以上代碼是如何調整這種可選的UI流的:標題Fragment對象被嵌入到該Activity內部的明細Fragment對象中,並且如果Fragment對象運行在一個有顯示明細空間的配置環境中,那么明細Activity會由它自己來完成。

當由於配置的改變而導致Activity所持有的這些Fragment對象重啟的時候,它們新的Fragment實例可以使用與之前所使用的布局不同的布局。在這種情況中,之前所有的Fragment對象依然會被實例化,並運行在新的實例中。但是任何不在跟<fragment>關聯的View對象將不會再被創建,並且重isInLayout()方法中返回false

在把FragmentView對象綁定到父容器的時候,<fragment>標簽的屬性被用於控制提供給LayoutParams對象的信息,它們能夠作為Fragment對象中的onInflate(Activity, AttributeSet, Bundle)方法的參數來解析。

正在實例化的Fragment對象必須要有某些類型唯一標識,以便在它的父Activity在銷毀並重建的時候,能夠被重新關聯到之前的實例。可以使用以下方法來實現這種關聯:

1. 如果沒有明確的指定,則使用容器的View ID來標識;

2. 使用<fragment>元素的android:tag屬性,給Fragment對象元素提供一個特定的標簽名稱;

3. 使用<fragment>元素的android:id屬性,給Fragment對象的元素提供一個特定的標識。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM