android Fragments詳解七:fragement示例
下例中實驗了上面所講的所有內容。此例有一個activity,其含有兩個fragment。一個顯示莎士比亞劇的播放曲目,另一個顯示選中曲目的摘要。此例還演示瞭如何跟據螢幕大小配置fragment。
主activity建立layout。
- @Override
- protectedvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.fragment_layout);
- }
主activity的layoutxml文件
- <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>
系統在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"
- 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>
這個layout只包含TitlesFragment。這表示當使用豎屏時,只顯示標題列表。當使用者選中一項時,程式會啟動一個新的activity去顯示摘要,而不是載入第二個fragment。
下一步,你會看到Fragment類的實現。第一個是TitlesFragment,它從ListFragment派生,大部分列表的功能由ListFragment提供。
當使用者選擇一個Title時,程式碼需要做出兩種行為,一種是在同一個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,DetailsFragment顯示被選擇的Title的摘要:
- 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;
- }
- }
如果當前的layout沒有R.id.detailsView(它被用於DetailsFragment的容器),那麼程式就啟動DetailsActivity來顯示摘要。
下面是DetailsActivity,它只是簡單地嵌入DetailsFragment來顯示摘要。
- 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();
- }
- }
- }
注意這個activity在檢測到是豎屏時會結束自己,於是主activity會接管它並顯示出TitlesFragment和DetailsFragment。這可以在使用者在豎屏時顯示在TitleFragment,但使用者旋轉了螢幕,使顯示變成了橫屏。
轉自:http://blog.csdn.net/niu_gao/article/details/7197255
相關文章
- android Fragments詳解六:處理fragement的生命週期AndroidFragment
- android Fragments詳解一:概述AndroidFragment
- android Fragments詳解二:建立FragmentAndroidFragment
- android Fragments詳解四:管理fragmentAndroidFragment
- android Fragments詳解五:與activity通訊AndroidFragment
- android Fragments詳解三:實現Fragment的介面AndroidFragment
- Android中使用FragmentManager管理fragmentsAndroidFragment
- HashMap詳解七HashMap
- 七. Vue Router詳解Vue
- sed 命令詳解及示例
- Android 3.0開始引入fragments(碎片、片段)類AndroidFragment
- OSI七層模型詳解模型
- Java集合(七) Queue詳解Java
- cdMysql?using?用法示例詳解MySql
- 關於Fragement的學習
- ELK詳解(七)——Kibana部署
- curl常用引數詳解及示例
- 在Android Studio中利用List Fragments建立相簿GalleryAndroidFragment
- Flutter 佈局(七)- Row、Column詳解Flutter
- Git詳解之七:自定義GitGit
- 第七講 顯示例表
- Android ViewPager Fragments滑動只重新整理當前頁AndroidViewpagerFragment
- fwMySql資料型別教程示例詳解MySql資料型別
- Linux 中 crontab 詳解及示例(收藏)Linux
- Android AsyncTask 詳解Android
- Android:動畫詳解Android動畫
- Android拖拽詳解Android
- Android:Service詳解Android
- Android Notification 詳解Android
- Android WebView 詳解AndroidWebView
- Android – Drawable 詳解Android
- Android RecyclerView詳解AndroidView
- Android Proguard 詳解Android
- android service詳解Android
- Spring @Conditional註解 詳細講解及示例Spring
- OSI七層網路結構詳解
- 七種網路卡繫結模式詳解模式
- 淺談JavaScript程式碼預解析 + 示例詳解JavaScript