Android 4學習(8):使用者介面 - Fragment

來源:互聯網
上載者:User

參考《Professional Android 4 Development》

Fragment簡介

Fragment是我們可以將Activity分成不同的組成部分,這些組成部分擁有自己的生命週期和UI。它的最大用途在於適配不同的螢幕。 建立Fragment

Fragment和Activity有很多相似之處,例如可以不帶UI,但這樣做對兩者似乎都沒什麼意義。他們的建立方式也很相似,例如下面的代碼:

package test.fragments;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class MySkeletonFragment extends Fragment {@Overridepublic View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {  // Create, or inflate the Fragment’s UI, and return it.  // If this Fragment has no UI then return null.  return inflater.inflate(R.layout.my_fragment, container, false);  }}
Fragment生命週期

Fragment的生命週期和它的宿主Activity密切相關,幾乎和宿主Activity的生命週期一致,他們之間最大的不同在於Activity可以增加或刪除Fragment。下圖總結了Fragment的生命週期:

Fragment特有的生命週期事件

Attach and detach Fragment from the parent Activity Creating and destroying Fragment Creating and Destroying UI

擷取Fragment Manager

每個Activity對象都內建了一個FragmentManager對象,使用getFragmentManager()即可獲得:

FragmentManager fragmentManager = getFragmentManager(); 添加Fragment到Activity中

在Activity中添加Fragment的最簡單方法是使用layout設定檔,例如:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="horizontal"  android:layout_width="match_parent"  android:layout_height="match_parent">  <fragment android:name="com.paad.weatherstation.MyListFragment"  android:id="@+id/my_list_fragment"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="1"  />  <fragment android:name="com.paad.weatherstation.DetailsFragment"  android:id="@+id/details_fragment"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="3"  /></LinearLayout>

調用inflate方法產生Fragment的介面後,Fragment實際上是一個類似ViewGroup的角色,在Activity中管理自己的UI。

上面那種將Fragment添加到Activity的方法缺乏靈活性,不能實現動態地添加和刪除,更好的方式是使用FragmentTranaction和類似下面這樣的設定檔:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="horizontal"  android:layout_width="match_parent"  android:layout_height="match_parent">  <FrameLayout  android:id="@+id/ui_container"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="1"  />  <FrameLayout  android:id="@+id/details_container"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="3"  /></LinearLayout>
使用FragmentTransaction

FragmentTransaction可以在運行時添加,刪除或替換Fragment,從而實現UI的動態變化。Fragment Transaction由Fragment Manager的beginTransaction()方法建立,然後可以進行Fragment的添加,刪除和替換,最後通過commit()方法提交修改。

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();// Add, remove, and/or replace Fragments.// Specify animations.// Add to back stack if required.fragmentTransaction.commit();
添加,刪除和替換Fragment

使用FragmentTransaction的add方法可以添加一個新的Fragment,add()方法的主要參數是Fragment的容器View(或其ID)及Fragment執行個體,例如:

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();fragmentTransaction.add(R.id.ui_container, new MyListFragment());fragmentTransaction.commit();

刪除Fragment需要FragmentTransaction的remove()方法,參數為Fragment對象,Fragment對象可以通過FragmentManager的findFragmentById()方法獲得。

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();Fragment fragment = fragmentManager.findFragmentById(R.id.details_fragment);fragmentTransaction.remove(fragment);fragmentTransaction.commit();

替換Fragment使用的是FragmentTransaction的replace()方法,參數分別為所要替代Fragment所在容器的ID和新的Fragment:

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();fragmentTransaction.replace(R.id.details_fragment, new DetailFragment(selected_index));fragmentTransaction.commit();
擷取指定的Fragment

有兩種方法可以擷取某個特定的Fragment,如果這個Fragment已經被添加到某個layout檔案中,則可以使用xml檔案中的id作為參數:

MyFragment myFragment = (MyFragment)fragmentManager.findFragmentById(R.id.MyFragment);

也可以通過建立Fragment時添加的tag擷取特定的Fragment:

MyFragment myFragment = (MyFragment)fragmentManager.findFragmentByTag(MY_FRAGMENT_TAG);
刪除Fragment容器

在設定檔中將visibility的屬性設為"gone",即可刪除某個Fragment,例如:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="horizontal"  android:layout_width="match_parent"  android:layout_height="match_parent">  <FrameLayout  android:id="@+id/ui_container"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="1"  />  <FrameLayout  android:id="@+id/details_container"  android:layout_width="match_parent"  android:layout_height="match_parent"  android:layout_weight="3"  android:visibility="gone"  /></LinearLayout>
Fragment和Back Stack

Activity擁有Activity Stack,從而在使用者按”返回”按鈕時,回到前一個Activity。Fragment也可以響應”返回”事件,方法是FragmentTransaction在commit之前調用addToBackStack()方法。這樣,在使用者按返回鍵後,Android會首先重現之前的UI布局。

FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();fragmentTransaction.add(R.id.ui_container, new MyListFragment());Fragment fragment = fragmentManager.findFragmentById(R.id.details_fragment);fragmentTransaction.remove(fragment);String tag = null;fragmentTransaction.addToBackStack(tag);fragmentTransaction.commit();

原理和Activity類似,調用addToBackStack()後,Fragment會被push到back stack中,而不是銷毀。 Fragment Transaction的動畫效果

Fragment Transaction有兩種方法實現動畫效果,分別是:

設定漸進: transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

設定動畫效果:

fragmentTransaction.setCustomAnimations(R.animator.slide_in_left, R.animator.slide_out_right);

Fragment和宿主Activity之間的介面

Fragment可以通過getActivity()方法獲得宿主Activity對象:

TextView textView = (TextView)getActivity().findViewById(R.id.textview);

另一種常見的Fragment和Activity之間的互動方式是使用回呼函數:

public interface OnSeasonSelectedListener {  public void onSeasonSelected(Season season);}private OnSeasonSelectedListener onSeasonSelectedListener;  private Season currentSeason;  @Override  public void onAttach(Activity activity) {  super.onAttach(activity);  try {  onSeasonSelectedListener = (OnSeasonSelectedListener)activity;  } catch (ClassCastException e) {  throw new ClassCastException(activity.toString() +"must implement OnSeasonSelectedListener");  }  }  private void setSeason(Season season) {  currentSeason = season;  onSeasonSelectedListener.onSeasonSelected(season);}
沒有UI的Fragment 儘管不常見,但Fragment的確是可以沒有UI的,好處也許是擁有了更靈活的生命週期控制。沒有UI的Fragment生命週期事件有這些:
public class NewItemFragment extends Fragment {  @Override  public void onAttach(Activity activity) {  super.onAttach(activity); // Get a type-safe reference to the parent Activity.  }  @Override    public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  // Create background worker threads and tasks.  }  @Override  public void onActivityCreated(Bundle savedInstanceState) {  super.onActivityCreated(savedInstanceState);  // Initiate worker threads and tasks.  }}
常用的Fragment類 DiagFragment ListFragment webViewFragment

















聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.