Fragments | Android Developer

來源:互聯網
上載者:User

標籤:des   android   style   blog   io   ar   color   os   使用   

Definition
  • A Fragment represents a behavior or a potion of user interface in an Activity.
  • You can combile multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities.
  • A Fragment has its own life cycle, receives its own input events, and you can add or remove it while the activity is running. (sub activity)
  • A Fragment‘s lifecycle is directly affected by its host activity‘s lifecycle. It follows the activity‘s lifecycle, except for in resuming state. The fragment‘s transaction can be pushed into the backstack.
Two ways to add a fragment to acitvity
  • Define <fragment>...</fragment> in layout file.
  • In code, add a fragment to an existing ViewGroup.
Design philosophy
  • 在3.0(API 11)出現,目的是滿足動態、靈活的UI設計,避免view hierarchy的頻繁變化。
  • 對於目的是複用的Fragment A,盡量避免在另一個Fragment B裡操作它的生命週期(因為在另一個情境下很可能就沒有B了)
Creating a fragment

在實現一個Fragment時,通常需要override以下方法

  • onCreate(),完成初始化功能
  • onCreateView(),Fragment首次繪製UI時會調用該方法,返回根View,如果Fragment不需要UI,則返回null
  • onPause(),commit changes

幾種Fragment

  • DialogFragment
  • ListFragment
  • PreferenceFragment

建立Fragment的幾種方法

  • 布局檔案裡聲明
<fragment android:name="com.example.news.ArticleListFragment"            android:id="@+id/list"       android:layout_weight="1"            android:layout_width="0dp"            android:layout_height="match_parent" />

 

 

  • Programmatically (in Activity)
FragmentManager fm = getFragmentManager();FragmentTransaction ft = fm.beginTransaction();SampleFragment f = new SampleFragment();ft.add(R.id.fragment_container, f);fm.commit();

 無UI的Fragment

  • 使用 add(Fragment fragment, String tag) 進行添加
  • 無需重寫 onCreateView 方法
  • 使用 findFragmentByTag 擷取該Fragment
Managing Fragments

FragmentManager 的作用

  • 擷取Fragment:findFragmentById(有UI),findFragmentByTag(無UI)
  • 使Fragment出棧,popBackStack(),類比使用者點擊Back按鈕。(用處何在?)
  • 在BackStack中增加Listener,addOnBackStackChangeListener()
Performing Fragment Transactions

使用BackStack來儲存Fragment的狀態

// Create new fragment and transactionFragment newFragment = new ExampleFragment();FragmentTransaction transaction = getFragmentManager().beginTransaction();// Replace whatever is in the fragment_container view with this fragment,// and add the transaction to the back stacktransaction.replace(R.id.fragment_container, newFragment);transaction.addToBackStack(null);// Commit the transactiontransaction.commit();

 

在commit()前使用setTransaction()來增加動畫效果

Communicating with the Activity

彼此擷取引用

  • Fragment通過getActivity()來擷取宿主Activity的引用
  • Activity通過getFragmentManager().findFragmentById()來擷取嵌入的Fragment引用

在Fragment中實現對Activity的Callback:聲明一個介面,在onAttach()時將實現該介面的Activity引用儲存,在需要通知Activity時調用介面中的方法

public static class FragmentA extends ListFragment {
  private OnArticleSelectedListener mListener; ... // Container Activity must implement this interface public interface OnArticleSelectedListener { public void onArticleSelected(Uri articleUri); } ... @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnArticleSelectedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener"); } } ... @Override public void onListItemClick(ListView l, View v, int position, long id) { // Append the clicked item‘s row ID with the content provider Uri Uri noteUri = ContentUris.withAppendedId(ArticleColumns.CONTENT_URI, id); // Send the event and Uri to the host activity mListener.onArticleSelected(noteUri); } ...}

 

 Fragment可以註冊Options Menu與Context Menu,從而接收到onOptionsItemSelected()等事件

Handling the Fragment Lifecycle

Fragment的生命週期與Activity類似

  • create階段,onAttach() -> onCreate() -> onCreateView() -> onActivityCreated()
  • 最大的不同在於Activity自動入棧,而Fragment需要顯式聲明

在宿主Activity的Resume階段,可以自由進行Fragment的增添/刪除

 

Fragments | Android Developer

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.