点击打开链接
Android Fragment学习笔记(二)
Note:本例有两个Fragment,并且Fragment之间能够进行通信,每当点击左边fragment的item时,都会在右边的fragment中显示对应的内容。需要整个工程的请到我的资源里下载fragmentlayou123.
本程序涉及3个.java文件:Fragmentlayout123Activity.java、DetailsFragment.java、TitleFragment.java。其中各个部分的功能如下:
1、在Fragmentlayout123Activity.java中,设置了fragment_layout布局,并建了一个DetailsActivity,用在手机上显示。
- public class Fragmentlayout123Activity extends Activity {
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.fragment_layout);
- }
- /**
- * This is a secondary activity, to show what the user has selected
- * when the screen is not large enough to show it all in one activity.
- */
- public 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();
- }
- }
- }
- }
2、在DetailsFragment.java中,方法newInstance用于新建一个DetailFragment,onCreateView用来产生DetailFragment的View。
- public 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);
- //给Fragment初始化参数
- 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());
- // hetao:设置边框大小
- text.setPadding(padding, padding, padding, padding);
- scroller.addView(text);
- text.setText(DIALOGUE[getShownIndex()]);
- return scroller;
- }
- public static final String[] DIALOGUE = {
- "So shaken as we are, so wan with care,"
- + "In forwarding this dear expedience.",
- "Hear him but reason in divinity,"
- + "From open haunts and popularity.",
- "I come no more to make you laugh: things now,"
- + "A man may weep upon his wedding-day.",
- "First, heaven be the record to my speech!"
- + "What my tongue speaks my right drawn sword may prove.",
- "Now is the winter of our discontent"
- + "Clarence comes.",
- "To bait fish withal: if it will feed nothing else,"
- + "will better the instruction.",
- "Virtue! a fig! 'tis in ourselves that we are thus"
- + "you call love to be a sect or scion.",
- "Blow, winds, and crack your cheeks! rage! blow!"};
- public static final String[] TITLES = { "Henry IV (1)", "Henry V",
- "Henry VIII", "Richard II", "Richard III", "Merchant of Venice",
- "Othello", "King Lear" };
- }
3、在TitleFragment.java中,onActivityCreated用来初始化TitleFragment,showDetails用来显示选中Item的内容。
- public class TitlesFragment extends ListFragment {
- boolean mDualPane; //检验是否有DetailFragment,没有就另起一个activity
- int mCurCheckPosition = 0;
- @Override
- //初始化TitleFragment
- 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, 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) {
- 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);
- }
- }
- //copied by hetao
- public static final String[] TITLES =
- {
- "Henry IV (1)",
- "Henry V",
- "Henry VIII",
- "Richard II",
- "Richard III",
- "Merchant of Venice",
- "Othello",
- "King Lear"
- };
- }
其中还涉及到一个布局文件fragment_layout.xml
- <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="haha.com.cn.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>