下例中實驗了上面所講的所有內容。此例有一個activity,其含有兩個fragment。一個顯示莎士比亞劇的播放曲目,另一個顯示選中曲目的摘要。此例還示範了如何跟據螢幕大小配置fragment。
主activity建立layout。
@Override<br />protectedvoid onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);</p><p> setContentView(R.layout.fragment_layout);<br />}
主activity的layoutxml文檔
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:orientation="horizontal"<br /> android:layout_width="match_parent" android:layout_height="match_parent"></p><p> <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"<br /> android:id="@+id/titles" android:layout_weight="1"<br /> android:layout_width="0px" android:layout_height="match_parent" /></p><p> <FrameLayout android:id="@+id/details" android:layout_weight="1"<br /> android:layout_width="0px" android:layout_height="match_parent"<br /> android:background="?android:attr/detailsElementBackground" /></p><p></LinearLayout>
系統在activity載入此layout時初始化TitlesFragment(用於顯示標題列表),TitlesFragment的右邊是一個FrameLayout,用於存放顯示摘要的fragment,但是現在它還是空的,fragment只有當使用者選擇了一項標題後,摘要fragment才會被放到FrameLayout中。
然而,並不是所有的螢幕都有足夠的寬度來容納標題列表和摘要。所以,上述layout只用於橫屏,現把它存放於ret/layout-land/fragment_layout.xml。
之外,當用於豎屏時,系統使用下面的layout,它存放於ret/layout/fragment_layout.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:layout_width="match_parent" android:layout_height="match_parent"><br /> <fragment class="com.example.android.apis.app.FragmentLayout$TitlesFragment"<br /> android:id="@+id/titles"<br /> android:layout_width="match_parent" android:layout_height="match_parent" /><br /></FrameLayout>
這個layout只包含TitlesFragment。這表示當使用豎屏時,只顯示標題列表。當使用者選中一項時,程式會啟動一個新的activity去顯示摘要,而不是載入第二個fragment。
下一步,你會看到Fragment類的實現。第一個是TitlesFragment,它從ListFragment派生,大部分列表的功能由ListFragment提供。
當使用者選擇一個Title時,代碼需要做出兩種行為,一種是在同一個activity中顯示建立並顯示摘要fragment,另一種是啟動一個新的activity。
public static class TitlesFragment extends ListFragment {<br /> boolean mDualPane;<br /> int mCurCheckPosition = 0;</p><p> @Override<br /> public void onActivityCreated(Bundle savedInstanceState) {<br /> super.onActivityCreated(savedInstanceState);</p><p> // Populate list with our static array of titles.<br /> setListAdapter(new ArrayAdapter<String>(getActivity(),<br /> android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));</p><p> // Check to see if we have a frame in which to embed the details<br /> // fragment directly in the containing UI.<br /> View detailsFrame = getActivity().findViewById(R.id.details);<br /> mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;</p><p> if (savedInstanceState != null) {<br /> // Restore last state for checked position.<br /> mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);<br /> }</p><p> if (mDualPane) {<br /> // In dual-pane mode, the list view highlights the selected item.<br /> getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);<br /> // Make sure our UI is in the correct state.<br /> showDetails(mCurCheckPosition);<br /> }<br /> }</p><p> @Override<br /> public void onSaveInstanceState(Bundle outState) {<br /> super.onSaveInstanceState(outState);<br /> outState.putInt("curChoice", mCurCheckPosition);<br /> }</p><p> @Override<br /> public void onListItemClick(ListView l, View v, int position, long id) {<br /> showDetails(position);<br /> }</p><p> /**<br /> * Helper function to show the details of a selected item, either by<br /> * displaying a fragment in-place in the current UI, or starting a<br /> * whole new activity in which it is displayed.<br /> */<br /> void showDetails(int index) {<br /> mCurCheckPosition = index;</p><p> if (mDualPane) {<br /> // We can display everything in-place with fragments, so update<br /> // the list to highlight the selected item and show the data.<br /> getListView().setItemChecked(index, true);</p><p> // Check what fragment is currently shown, replace if needed.<br /> DetailsFragment details = (DetailsFragment)<br /> getFragmentManager().findFragmentById(R.id.details);<br /> if (details == null || details.getShownIndex() != index) {<br /> // Make new fragment to show this selection.<br /> details = DetailsFragment.newInstance(index);</p><p> // Execute a transaction, replacing any existing fragment<br /> // with this one inside the frame.<br /> FragmentTransaction ft = getFragmentManager().beginTransaction();<br /> ft.replace(R.id.details, details);<br /> ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);<br /> ft.commit();<br /> }</p><p> } else {<br /> // Otherwise we need to launch a new activity to display<br /> // the dialog fragment with selected text.<br /> Intent intent = new Intent();<br /> intent.setClass(getActivity(), DetailsActivity.class);<br /> intent.putExtra("index", index);<br /> startActivity(intent);<br /> }<br /> }
第二個fragment,DetailsFragment顯示被選擇的Title的摘要:
public static class DetailsFragment extends Fragment {<br /> /**<br /> * Create a new instance of DetailsFragment, initialized to<br /> * show the text at 'index'.<br /> */<br /> public static DetailsFragment newInstance(int index) {<br /> DetailsFragment f = new DetailsFragment();</p><p> // Supply index input as an argument.<br /> Bundle args = new Bundle();<br /> args.putInt("index", index);<br /> f.setArguments(args);</p><p> return f;<br /> }</p><p> public int getShownIndex() {<br /> return getArguments().getInt("index", 0);<br /> }</p><p> @Override<br /> public View onCreateView(LayoutInflater inflater, ViewGroup container,<br /> Bundle savedInstanceState) {<br /> if (container == null) {<br /> // We have different layouts, and in one of them this<br /> // fragment's containing frame doesn't exist. The fragment<br /> // may still be created from its saved state, but there is<br /> // no reason to try to create its view hierarchy because it<br /> // won't be displayed. Note this is not needed -- we could<br /> // just run the code below, where we would create and return<br /> // the view hierarchy; it would just never be used.<br /> return null;<br /> }</p><p> ScrollView scroller = new ScrollView(getActivity());<br /> TextView text = new TextView(getActivity());<br /> int padding = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,<br /> 4, getActivity().getResources().getDisplayMetrics());<br /> text.setPadding(padding, padding, padding, padding);<br /> scroller.addView(text);<br /> text.setText(Shakespeare.DIALOGUE[getShownIndex()]);<br /> return scroller;<br /> }<br />}
如果當前的layout沒有R.id.detailsView(它被用於DetailsFragment的容器),那麼程式就啟動DetailsActivity來顯示摘要。
下面是DetailsActivity,它只是簡單地嵌入DetailsFragment來顯示摘要。
public static class DetailsActivity extends Activity {</p><p> @Override<br /> protected void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);</p><p> if (getResources().getConfiguration().orientation<br /> == Configuration.ORIENTATION_LANDSCAPE) {<br /> // If the screen is now in landscape mode, we can show the<br /> // dialog in-line with the list so we don't need this activity.<br /> finish();<br /> return;<br /> }</p><p> if (savedInstanceState == null) {<br /> // During initial setup, plug in the details fragment.<br /> DetailsFragment details = new DetailsFragment();<br /> details.setArguments(getIntent().getExtras());<br /> getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();<br /> }<br /> }<br />}
注意這個activity在檢測到是豎屏時會結束自己,於是主activity會接管它並顯示出TitlesFragment和DetailsFragment。這可以在使用者在豎屏時顯示在TitleFragment,但使用者旋轉了螢幕,使顯示變成了橫屏。