Updated: 23 April 2013
Tested in:
HTC desire S (android 2.3.5), Samsung Galaxy Ace (android 2.3.4), Samsung Galaxy Tab P3100 (android 4.0.4)
Base on:
Eclipse Indigo build in 20120216-1857, Java 1.6, Android 4.1.2
Download Source code:
FragmentMultipleIntances20130423.rar
Description:
Using when one screen or one function must exist multiple times in backstack with different data.
Screen shot:
Tutorial:
Create the code in fragment:
/**
* Create a new instance of this fragment
*/
public static MultipleFragment newInstance(int fragmentID) {
MultipleFragment newFragment = new MultipleFragment();
Bundle args = new Bundle();
args.putInt("FragmentID", fragmentID);
newFragment.setArguments(args);
return newFragment;
}
And when click to open a new instance of fragment, using this code below:public void openNewFragment() {
Fragment newFragment = null;
FragmentTransaction ft = mFragmentManager.beginTransaction();
if (mStack.isEmpty() == true) {
/**
* No fragment created, open the first instance with id = 1
*/
newFragment = MultipleFragment.newInstance(1);
ft.add(R.id.content, newFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.show(newFragment);
} else {
/**
* Stack is not empty, open a new instance
*/
// Hide the last fragment
ft.hide(mListFragments.get(mStackUniqueID.lastElement()));
// Show the new fragment
int newID = mStack.size() + 1;
newFragment = MultipleFragment.newInstance(newID);
ft.add(R.id.content, newFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.show(newFragment);
}
// add this new fragment to stack
if (newFragment != null) {
mStack.push(newFragment.getClass().getSimpleName());
String fragmentID = createTimeStamp();
mListFragments.put(fragmentID, newFragment);
mStackUniqueID.push(fragmentID);
}
ft.commit();
}