joielechong

Fragment Communication Example

Nov 25th, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1.  
  2. /////////////////////////////////////////////////////////////////////////////////
  3. // ContentListFragment
  4. ////////////////////////////////////////////////////////////////////////////////
  5. private int             mBookTypeId;
  6. private final static String     BOOK_TYPE_ID    = "BOOKTYPE_ID";
  7.  
  8. public ContentListFragment() {}
  9.  
  10. /**
  11. * Returns a new instance of this fragment for the given section number.
  12. */
  13. public static ContentListFragment newInstance(int bookTypeId) {
  14.    ContentListFragment fragment = new ContentListFragment();
  15.    Bundle args = new Bundle();
  16.    args.putInt(BOOK_TYPE_ID, bookTypeId);
  17.    fragment.setArguments(args);
  18.    return fragment;
  19. }
  20.  
  21.  
  22. /**
  23.  * This method will only be called once when the retained Fragment is first
  24.  * created.
  25.  */
  26. @Override
  27. public void onCreate(Bundle savedInstanceState) {
  28.    super.onCreate(savedInstanceState);
  29.    setRetainInstance(true);
  30.    Bundle args = getArguments();
  31.    mBookTypeId = args.getInt(BOOK_TYPE_ID);
  32. }
  33.  
  34.  
  35. /////////////////////////////////////////////////////////////////////////////////////////////////////////
  36. // MainActivity
  37. ////////////////////////////////////////////////////////////////////////////////////////////////////////
  38. int mBookNumber = 1;
  39. public static final String  CONTENT_LIST_FRAGMENT_TAG   = "ContentListFragment";
  40. private FragmentTransaction     mFragmentTransaction                = null;
  41. @Override
  42. public void onCreate(Bundle savedInstanceState) {
  43.    super.onCreate(savedInstanceState);     
  44.    if (savedInstanceState == null) {   
  45.       mFragmentTransaction = getSupportFragmentManager().beginTransaction();
  46.       mFragmentTransaction.replace(R.id.content_frame,
  47.                                    ContentListFragment.newInstance(mBookNumber),
  48.                    CONTENT_LIST_FRAGMENT_TAG);
  49.       mFragmentTransaction.commit();
  50.    }
  51. }
Add Comment
Please, Sign In to add comment