Xem mẫu

  1. Trung tâm Tin học – ĐH KHTN Shakespeare Trong bài viết này, mình sẽ tạo ra 1 ứng dụng đọc sách nho nh ỏ đ ể thông qua đó demo cách thức hoạt động của Fragment trên Android 3.0 . Để đ ơn gi ản hóa ứng dụng, mình sẽ dùng 1 file Shakespeare.java để chưa tiêu đề và n ội dung s ơ l ược c ủa sách (các bạ có thể dùng file hay database…). Các bước thực hiện ứng d ụng nh ư sau: 1/ Tạo Project : Project name: ShakespeareInstrumented Build Target: Android 3.0 Application name: ShakespeareInstrumented Package name: com.dac.Shakespeare Create Activity: MainActivity 2/ Trong phần main.xml ta code như sau: Và ta thêm 1 file details.xml để thể hiện chi tiết (nội dung s ơ l ược): Lập trình Android – http://laptrinhdidong.vn Page 1
  2. Trung tâm Tin học – ĐH KHTN Để có thể test ứng dụng trên màn hình ngang thì ta thêm 1 folder layout-land trong m ục res/ và ta tạo file main.xml : 3/ Ta tạo 1 folder animator trong res/ và thêm các file XML sau: + bounce_in_down.xml: Lập trình Android – http://laptrinhdidong.vn Page 2
  3. Trung tâm Tin học – ĐH KHTN + fade_in.xml: + fade_out.xml: + slide_in_left.xml: + slide_out_down.xml:
  4. Trung tâm Tin học – ĐH KHTN android:duration="2000"> + slide_out_right.xml: 4/ Ở phần code xử lý, ta tạo thêm các class Java hỗ trợ: + Shakespeare.java để chứ tiêu đề và sợ lược của truyện: package com.androidbook.Shakespeare; public class Shakespeare { public static String TITLES[] = { "Henry IV (1)", "Henry V", "Henry VIII", "Romeo and Juliet", "Hamlet", "The Merchant of Venice", "Othello" }; public static String DIALOGUE[] = { "So shaken as we are, so wan with care,\n"+ "Find we a time for frighted peace to pant,\n"+ "And breathe short-winded accents of new broils\n"+ "To be commenced in strands afar remote.\n"+ "No more the thirsty entrance of this soil\n"+ "Shall daub her lips with her own children's blood;\n"+ "Nor more shall trenching war channel her fields,\n"+ "Nor bruise her flowerets with the armed hoofs\n"+ "Of hostile paces: those opposed eyes,\n"+ "Which, like the meteors of a troubled heaven,\n"+ "All of one nature, of one substance bred,\n"+ "Did lately meet in the intestine shock\n"+ "And furious close of civil butchery\n"+ "Shall now, in mutual well-beseeming ranks,\n"+ "March all one way and be no more opposed\n"+ "Against acquaintance, kindred and allies:\n"+ "The edge of war, like an ill-sheathed knife,\n"+ Lập trình Android – http://laptrinhdidong.vn Page 4
  5. Trung tâm Tin học – ĐH KHTN "No more shall cut his master. Therefore, friends,\n"+ "As far as to the sepulchre of Christ,\n"+ "Whose soldier now, under whose blessed cross\n"+ "We are impressed and engaged to fight,\n"+ "Forthwith a power of English shall we levy;\n"+ "Whose arms were moulded in their mothers' womb\n"+ "To chase these pagans in those holy fields\n"+ "Over whose acres walk'd those blessed feet\n"+ "Which fourteen hundred years ago were nail'd\n"+ "For our advantage on the bitter cross.\n"+ "But this our purpose now is twelve month old,\n"+ "And bootless 'tis to tell you we will go:\n"+ "Therefore we meet not now. Then let me hear\n"+ "Of you, my gentle cousin Westmoreland,\n"+ "What yesternight our council did decree\n"+ "In forwarding this dear expedience.", "O for a Muse of fire, that would ascend\n"+ "The brightest heaven of invention,\n"+ "A kingdom for a stage, princes to act\n"+ "And monarchs to behold the swelling scene!\n"+ "Then should the warlike Harry, like himself,\n"+ "Assume the port of Mars; and at his heels,\n"+ "Leash'd in like hounds, should famine, sword and fire\n"+ "Crouch for employment. But pardon, and gentles all,\n"+ "The flat unraised spirits that have dared\n"+ "On this unworthy scaffold to bring forth\n"+ "So great an object: can this cockpit hold\n"+ "The vasty fields of France? or may we cram\n"+ "Within this wooden O the very casques\n"+ "That did affright the air at Agincourt?\n"+ "O, pardon! since a crooked figure may\n"+ "Attest in little place a million;\n"+ "And let us, ciphers to this great accompt,\n"+ "On your imaginary forces work.\n"+ "Suppose within the girdle of these walls\n"+ "Are now confined two mighty monarchies,\n"+ "Whose high upreared and abutting fronts\n"+ "The perilous narrow ocean parts asunder:\n"+ "Piece out our imperfections with your thoughts;\n"+ "Into a thousand parts divide on man,\n"+ "And make imaginary puissance;\n"+ "Think when we talk of horses, that you see them\n"+ "Printing their proud hoofs i' the receiving earth;\n"+ "For 'tis your thoughts that now must deck our kings,\n"+ "Carry them here and there; jumping o'er times,\n"+ "Turning the accomplishment of many years\n"+ "Into an hour-glass: for the which supply,\n"+ "Admit me Chorus to this history;\n"+ "Who prologue-like your humble patience pray,\n"+ "Gently to hear, kindly to judge, our play.", "I come no more to make you laugh: things now,\n"+ "That bear a weighty and a serious brow,\n"+ Lập trình Android – http://laptrinhdidong.vn Page 5
  6. Trung tâm Tin học – ĐH KHTN "Sad, high, and working, full of state and woe,\n"+ "Such noble scenes as draw the eye to flow,\n"+ "We now present. Those that can pity, here\n"+ "May, if they think it well, let fall a tear;\n"+ "The subject will deserve it. Such as give\n"+ "Their money out of hope they may believe,\n"+ "May here find truth too. Those that come to see\n"+ "Only a show or two, and so agree\n"+ "The play may pass, if they be still and willing,\n"+ "I'll undertake may see away their shilling\n"+ "Richly in two short hours. Only they\n"+ "That come to hear a merry bawdy play,\n"+ "A noise of targets, or to see a fellow\n"+ "In a long motley coat guarded with yellow,\n"+ "Will be deceived; for, gentle hearers, know,\n"+ "To rank our chosen truth with such a show\n"+ "As fool and fight is, beside forfeiting\n"+ "Our own brains, and the opinion that we bring,\n"+ "To make that only true we now intend,\n"+ "Will leave us never an understanding friend.\n"+ "Therefore, for goodness' sake, and as you are known\n"+ "The first and happiest hearers of the town,\n"+ "Be sad, as we would make ye: think ye see\n"+ "The very persons of our noble story\n"+ "As they were living; think you see them great,\n"+ "And follow'd with the general throng and sweat\n"+ "Of thousand friends; then in a moment, see\n"+ "How soon this mightiness meets misery:\n"+ "And, if you can be merry then, I'll say\n"+ "A man may weep upon his wedding-day.", "Two households, both alike in dignity,\n"+ "In fair Verona, where we lay our scene,\n"+ "From ancient grudge break to new mutiny,\n"+ "Where civil blood makes civil hands unclean.\n"+ "From forth the fatal loins of these two foes\n"+ "A pair of star-cross'd lovers take their life;\n"+ "Whose misadventured piteous overthrows\n"+ "Do with their death bury their parents' strife.\n"+ "The fearful passage of their death-mark'd love,\n"+ "And the continuance of their parents' rage,\n"+ "Which, but their children's end, nought could remove,\n"+ "Is now the two hours' traffic of our stage;\n"+ "The which if you with patient ears attend,\n"+ "What here shall miss, our toil shall strive to mend.", "Though yet of Hamlet our dear brother's death\n"+ "The memory be green, and that it us befitted\n"+ "To bear our hearts in grief and our whole kingdom\n"+ "To be contracted in one brow of woe,\n"+ "Yet so far hath discretion fought with nature\n"+ "That we with wisest sorrow think on him,\n"+ "Together with remembrance of ourselves.\n"+ "Therefore our sometime sister, now our queen,\n"+ Lập trình Android – http://laptrinhdidong.vn Page 6
  7. Trung tâm Tin học – ĐH KHTN "The imperial jointress to this warlike state,\n"+ "Have we, as 'twere with a defeated joy,--\n"+ "With an auspicious and a dropping eye,\n"+ "With mirth in funeral and with dirge in marriage,\n"+ "In equal scale weighing delight and dole,--\n"+ "Taken to wife: nor have we herein barr'd\n"+ "Your better wisdoms, which have freely gone\n"+ "With this affair along. For all, our thanks.\n"+ "Now follows, that you know, young Fortinbras,\n"+ "Holding a weak supposal of our worth,\n"+ "Or thinking by our late dear brother's death\n"+ "Our state to be disjoint and out of frame,\n"+ "Colleagued with the dream of his advantage,\n"+ "He hath not fail'd to pester us with message,\n"+ "Importing the surrender of those lands\n"+ "Lost by his father, with all bonds of law,\n"+ "To our most valiant brother. So much for him.\n"+ "Now for ourself and for this time of meeting:\n"+ "Thus much the business is: we have here writ\n"+ "To Norway, uncle of young Fortinbras,--\n"+ "Who, impotent and bed-rid, scarcely hears\n"+ "Of this his nephew's purpose,--to suppress\n"+ "His further gait herein; in that the levies,\n"+ "The lists and full proportions, are all made\n"+ "Out of his subject: and we here dispatch\n"+ "You, good Cornelius, and you, Voltimand,\n"+ "For bearers of this greeting to old Norway;\n"+ "Giving to you no further personal power\n"+ "To business with the king, more than the scope\n"+ "Of these delated articles allow.\n"+ "Farewell, and let your haste commend your duty.", "The quality of mercy is not strain'd,\n"+ "It droppeth as the gentle rain from heaven\n"+ "Upon the place beneath: it is twice blest;\n"+ "It blesseth him that gives and him that takes:\n"+ "'Tis mightiest in the mightiest: it becomes\n"+ "The throned monarch better than his crown;\n"+ "His sceptre shows the force of temporal power,\n"+ "The attribute to awe and majesty,\n"+ "Wherein doth sit the dread and fear of kings;\n"+ "But mercy is above this sceptred sway;\n"+ "It is enthroned in the hearts of kings,\n"+ "It is an attribute to God himself;\n"+ "And earthly power doth then show likest God's\n"+ "When mercy seasons justice. Therefore, Jew,\n"+ "Though justice be thy plea, consider this,\n"+ "That, in the course of justice, none of us\n"+ "Should see salvation: we do pray for mercy;\n"+ "And that same prayer doth teach us all to render\n"+ "The deeds of mercy. I have spoke thus much\n"+ "To mitigate the justice of thy plea;\n"+ "Which if thou follow, this strict court of Venice\n"+ Lập trình Android – http://laptrinhdidong.vn Page 7
  8. Trung tâm Tin học – ĐH KHTN "Must needs give sentence 'gainst the merchant there.", "It is Othello's pleasure, our noble and valiant\n"+ "general, that, upon certain tidings now arrived,\n"+ "importing the mere perdition of the Turkish fleet,\n"+ "every man put himself into triumph; some to dance,\n"+ "some to make bonfires, each man to what sport and\n"+ "revels his addiction leads him: for, besides these\n"+ "beneficial news, it is the celebration of his\n"+ "nuptial. So much was his pleasure should be\n"+ "proclaimed. All offices are open, and there is full\n"+ "liberty of feasting from this present hour of five\n"+ "till the bell have told eleven. Heaven bless the\n"+ "isle of Cyprus and our noble general Othello!" }; } + TitkesFragment.java: package com.dac.Shakespeare; import android.app.Activity; import android.app.ListFragment; import android.os.Bundle; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; public class TitlesFragment extends ListFragment { private MainActivity myActivity = null; int mCurCheckPosition = 0; @Override public void onInflate(AttributeSet attrs, Bundle icicle) { Log.v(MainActivity.TAG, "in TitlesFragment onInflate. AttributeSet contains:"); for(int i=0; i
  9. Trung tâm Tin học – ĐH KHTN this.myActivity = (MainActivity)myActivity; } @Override public void onCreate(Bundle icicle) { Log.v(MainActivity.TAG, "in TitlesFragment onCreate. Bundle contains:"); if(icicle != null) { for(String key : icicle.keySet()) { Log.v(MainActivity.TAG, " " + key); } } else { Log.v(MainActivity.TAG, " myBundle is null"); } super.onCreate(icicle); if (icicle != null) { mCurCheckPosition = icicle.getInt("curChoice", 0); } } @Override public View onCreateView(LayoutInflater myInflater, ViewGroup container, Bundle icicle) { Log.v(MainActivity.TAG, "in TitlesFragment onCreateView. container is " + container); return super.onCreateView(myInflater, container, icicle); } @Override public void onActivityCreated(Bundle icicle) { Log.v(MainActivity.TAG, "in TitlesFragment onActivityCreated. icicle contains:"); if(icicle != null) { for(String key : icicle.keySet()) { Log.v(MainActivity.TAG, " " + key); } } else { Log.v(MainActivity.TAG, " icicle is null"); } super.onActivityCreated(icicle); setListAdapter(new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, Shakespeare.TITLES)); ListView lv = getListView(); lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE); lv.setSelection(mCurCheckPosition); myActivity.showDetails(mCurCheckPosition); } Lập trình Android – http://laptrinhdidong.vn Page 9
  10. Trung tâm Tin học – ĐH KHTN @Override public void onStart() { Log.v(MainActivity.TAG, "in TitlesFragment onStart"); super.onStart(); } @Override public void onResume() { Log.v(MainActivity.TAG, "in TitlesFragment onResume"); super.onResume(); } @Override public void onPause() { Log.v(MainActivity.TAG, "in TitlesFragment onPause"); super.onPause(); } @Override public void onSaveInstanceState(Bundle icicle) { Log.v(MainActivity.TAG, "in TitlesFragment onSaveInstanceState"); super.onSaveInstanceState(icicle); icicle.putInt("curChoice", mCurCheckPosition); } @Override public void onListItemClick(ListView l, View v, int pos, long id) { Log.v(MainActivity.TAG, "in TitlesFragment onListItemClick. pos = " + pos); myActivity.showDetails(pos); mCurCheckPosition = pos; } @Override public void onStop() { Log.v(MainActivity.TAG, "in TitlesFragment onStop"); super.onStop(); } @Override public void onDestroyView() { Log.v(MainActivity.TAG, "in TitlesFragment onDestroyView"); super.onDestroyView(); } @Override public void onDestroy() { Log.v(MainActivity.TAG, "in TitlesFragment onDestroy"); super.onDestroy(); } Lập trình Android – http://laptrinhdidong.vn Page 10
  11. Trung tâm Tin học – ĐH KHTN @Override public void onDetach() { Log.v(MainActivity.TAG, "in TitlesFragment onDetach"); super.onDetach(); myActivity = null; } } + DetailsActivity.java: package com.dac.Shakespeare; import android.app.Activity; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; public class DetailsActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { Log.v(MainActivity.TAG, "in DetailsActivity onCreate"); super.onCreate(savedInstanceState); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { finish(); return; } if(getIntent() != null) { DetailsFragment details = DetailsFragment.newInstance(getIntent().getExtras()); getFragmentManager().beginTransaction() .add(android.R.id.content, details) .commit(); } } } + DetailsFragment.java: package com.dac.Shakespeare; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.util.AttributeSet; Lập trình Android – http://laptrinhdidong.vn Page 11
  12. Trung tâm Tin học – ĐH KHTN import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class DetailsFragment extends Fragment { private int mIndex = 0; public static DetailsFragment newInstance(int index) { Log.v(MainActivity.TAG, "in DetailsFragment newInstance(" + index + ")"); DetailsFragment df = new DetailsFragment(); Bundle args = new Bundle(); args.putInt("index", index); df.setArguments(args); return df; } public static DetailsFragment newInstance(Bundle bundle) { int index = bundle.getInt("index", 0); return newInstance(index); } @Override public void onInflate(AttributeSet attrs, Bundle savedInstanceState) { Log.v(MainActivity.TAG, "in DetailsFragment onInflate. AttributeSet contains:"); for(int i=0; i
  13. Trung tâm Tin học – ĐH KHTN Log.v(MainActivity.TAG, " myBundle is null"); } super.onCreate(myBundle); mIndex = getArguments().getInt("index", 0); } public int getShownIndex() { return mIndex; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Log.v(MainActivity.TAG, "in DetailsFragment onCreateView. container = " + container); View v = inflater.inflate(R.layout.details, container, false); TextView text1 = (TextView) v.findViewById(R.id.text1); text1.setText(Shakespeare.DIALOGUE[ mIndex ] ); return v; } @Override public void onActivityCreated(Bundle savedState) { Log.v(MainActivity.TAG, "in DetailsFragment onActivityCreated. savedState contains:"); if(savedState != null) { for(String key : savedState.keySet()) { Log.v(MainActivity.TAG, " " + key); } } else { Log.v(MainActivity.TAG, " savedState is null"); } super.onActivityCreated(savedState); } @Override public void onStart() { Log.v(MainActivity.TAG, "in DetailsFragment onStart"); super.onStart(); } @Override public void onResume() { Log.v(MainActivity.TAG, "in DetailsFragment onResume"); super.onResume(); } @Override Lập trình Android – http://laptrinhdidong.vn Page 13
  14. Trung tâm Tin học – ĐH KHTN public void onPause() { Log.v(MainActivity.TAG, "in DetailsFragment onPause"); super.onPause(); } @Override public void onSaveInstanceState(Bundle outState) { Log.v(MainActivity.TAG, "in DetailsFragment onSaveInstanceState"); super.onSaveInstanceState(outState); } @Override public void onStop() { Log.v(MainActivity.TAG, "in DetailsFragment onStop"); super.onStop(); } @Override public void onDestroyView() { Log.v(MainActivity.TAG, "in DetailsFragment onDestroyView, view = " + getView()); super.onDestroyView(); } @Override public void onDestroy() { Log.v(MainActivity.TAG, "in DetailsFragment onDestroy"); super.onDestroy(); } @Override public void onDetach() { Log.v(MainActivity.TAG, "in DetailsFragment onDetach"); super.onDetach(); } } + MainActivity.java: package com.dac.Shakespeare; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; Lập trình Android – http://laptrinhdidong.vn Page 14
  15. Trung tâm Tin học – ĐH KHTN public class MainActivity extends Activity { public static final String TAG = "Shakespeare"; @Override public void onCreate(Bundle savedInstanceState) { Log.v(TAG, "in MainActivity onCreate"); super.onCreate(savedInstanceState); FragmentManager.enableDebugLogging(true); setContentView(R.layout.main); } @Override public void onAttachFragment(Fragment fragment) { Log.v(TAG, "in MainActivity onAttachFragment. fragment id = " + fragment.getId()); super.onAttachFragment(fragment); } @Override public void onStart() { Log.v(TAG, "in MainActivity onStart"); super.onStart(); } @Override public void onResume() { Log.v(TAG, "in MainActivity onResume"); super.onResume(); } @Override public void onPause() { Log.v(TAG, "in MainActivity onPause"); super.onPause(); } @Override public void onStop() { Log.v(TAG, "in MainActivity onStop"); super.onStop(); } @Override public void onSaveInstanceState(Bundle outState) { Log.v(MainActivity.TAG, "in MainActivity onSaveInstanceState"); super.onSaveInstanceState(outState); } @Override public void onDestroy() { Log.v(TAG, "in MainActivity onDestroy"); super.onDestroy(); Lập trình Android – http://laptrinhdidong.vn Page 15
  16. Trung tâm Tin học – ĐH KHTN } public boolean isMultiPane() { return getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE; } public void showDetails(int index) { Log.v(TAG, "in MainActivity showDetails(" + index + ")"); if (isMultiPane()) { DetailsFragment details = (DetailsFragment) getFragmentManager().findFragmentById(R.id.details); if (details == null || details.getShownIndex() != index) { details = DetailsFragment.newInstance(index); Log.v(TAG, "about to run FragmentTransaction..."); FragmentTransaction ft = getFragmentManager().beginTransaction(); ft.setCustomAnimations(R.animator.bounce_in_down, R.animator.slide_out_down); ft.replace(R.id.details, details); ft.commit(); getFragmentManager().executePendingTransactions(); } } else { Intent intent = new Intent(); intent.setClass(this, DetailsActivity.class); intent.putExtra("index", index); startActivity(intent); } } } Và cuố cùng ta chỉ còn chỉnh lại trong AndroidManifest.xml : Lập trình Android – http://laptrinhdidong.vn Page 16
  17. Trung tâm Tin học – ĐH KHTN Debug ứng dụng các bạn sẽ được như sau : Mọi ý kiến đóng góp các bạn vui lòng gữi về http://forum.laptrinhdidong.vn . Rất mong nhận được sự phản hồi của các bạn. Lập trình Android – http://laptrinhdidong.vn Page 17
nguon tai.lieu . vn