I am using options menu in action bar tabs,view pager and nested fragments, when i switch from fragmentA to fragmentB using tabs menu items are working fine, but when i try to swith using view pager option items are getting invisble in fragments.
public class RTHomeTabFragment extends Fragment implements TabListener,OnBackButtonPressInterfaceForFragment{
public ActionBarActivity parentActivity;
private ActionBar actionBar;
ViewPager mViewPager;
public static int currentPage;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RTMessagingUtils.log(getClass().getName(), "onCreateView");
View view = inflater.inflate(R.layout.viewpager_tabs, container,false);
parentActivity = (ActionBarActivity) getActivity();
actionBar = parentActivity.getSupportActionBar();
mViewPager = (ViewPager) view.findViewById(R.id.pager);
/* actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);*/
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setCustomView(null);
actionBar.removeAllTabs();
List<Fragment> fragments = getFragments();
pagerAdapter adapter = new pagerAdapter(getChildFragmentManager(), getFragments());
mViewPager.setAdapter(adapter);
currentPage=mViewPager.getCurrentItem();
Log.d("TestFragments", "currentPage======"+currentPage);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
currentPage=mViewPager.getCurrentItem();
Log.d("TestFragments", "currentPage======"+currentPage);
}
});
for (int i = 0; i < adapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(adapter.getPageTitle(i)).setTabListener(this));
}
return view;
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// add fragments here
fList.add(new Test1());
fList.add(new Test2());
fList.add(new Test3());
return fList;
}
class pagerAdapter extends FragmentPagerAdapter{
private List<Fragment> fragments;
public pagerAdapter(FragmentManager fm, List<Fragment> fragments){
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.db_jio_chat_chats).toUpperCase(l);
case 1:
return getString(R.string.db_jio_chat_groups).toUpperCase(l);
case 2:
return getString(R.string.db_jio_chat_contacts).toUpperCase(l);
/*case 3:
return getString(R.string.db_jio_chat_my_profile).toUpperCase(l);
case 4:
return getString(R.string.db_jio_chat_location).toUpperCase(l);
case 5:
return getString(R.string.db_jio_chat_about).toUpperCase(l);*/
}
return null;
}
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
// setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
mViewPager.setCurrentItem(arg0.getPosition());
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onResume() {
super.onResume();
RTMessagingUtils.log(getClass().getName(), "onResume");
}
#Override
public void onPause() {
super.onPause();
RTMessagingUtils.log(getClass().getName(), "onPause");
}
}
In your getItem method do this for testing :
#Override
public Fragment getItem(int position) {
if(position == 0)
return new Test1();
else
return new Test2();
}
and see if this works, I will find an explanation later if it works...
Related
I have an activity and pager adapter in it which displays 3 fragments. The fragments are shuffled. I need to know the number of each page when I am swiping through them and that number needs to be displayed in a textView. For example, when I am in the first page number 1 is displayed, second page - number 2 and so on.
PagerAdapter.java
public class PagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int arg0) {
return this.fragments.get(arg0);
}
#Override
public int getCount() {
return this.fragments.size();
}
public void setFragments(List<Fragment> fragments) {
this.fragments = fragments;
}
}
mainActivity.java
public class testActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager_adapter);
initialisePaging();
}
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,fragment1.class.getName()));
fragments.add(Fragment.instantiate(this,fragment2.class.getName()));
fragments.add(Fragment.instantiate(this,fragment3.class.getName()));
PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
Collections.shuffle(fragments, new Random(System.nanoTime()));
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_test, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
If you want to be displaying the number in your fragment, use this
In your Activity
#Override
public Fragment getItem(int position) {
// Here you can add an argument that will be passed to the fragment
// In your case you need to pass the page number
Fragment fragment = this.fragments.get(arg0);
Bundle b = new Bundle();
b.putInt("page_number", position);
fragment.setArguments(b);
return fragment;
}
In you fragment do this
int number;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read the data that Activity passed to us
if (savedInstanceState == null) {
Bundle args = getArguments();
if (args != null) {
number = args.getInt("page_number") + 1;
}
}
else {
number = savedInstanceState.getInt("page_number");
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// Here you need to find your TextView and show the number
View v = inflater.inflate(R.layout.some_layout, container, false);
((TextView) v.findViewById(R.id.someTextView)).setText(String.format("%d", number));
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("page_number", number);
}
If you want to be displaying the number in your Activity, use this
private void initialisePaging() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,fragment1.class.getName()));
fragments.add(Fragment.instantiate(this,fragment2.class.getName()));
fragments.add(Fragment.instantiate(this,fragment3.class.getName()));
PagerAdapter mPagerAdapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
Collections.shuffle(fragments, new Random(System.nanoTime()));
// !!! Change ME!!!!!
textView = (TextView) findViewById(R.id.someTextView);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
textView.setText("Position: " + i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
pager.setAdapter(mPagerAdapter);
}
Use PageChangeListener as:
yourPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position)
{
yourTextView.setText("Page: " + position);
}
... ...
});
My App is a fragment have viewpager to change tab with fragmentA and fragmentB.
After I change another fragment by drawlayout.
I back to the first fragment.
The fragmentA and fragmentB doesn't link with the viewpager.
I think it's about Fragment cyclelife questions.
But I can't figure out the answer.
Please help me.Thanks.
(My English is not very well.Please use simple word.Thanks)
public class Fragment_Viewpager extends Fragment implements TabListener{
private View v;
ViewPager viewPager;
ActionBar actionBar;
ActionBar.Tab tab1;
ActionBar.Tab tab2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v= inflater.inflate(R.layout.fragment_viewpager, container, false);
viewPager=(ViewPager)v.findViewById(R.id.pager);
Log.w("Step1","inviewPager");
viewPager.setAdapter(new MyAdapter(getFragmentManager()));
Log.w("Step2","inviewPager");
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO 自動產生的方法 Stub
actionBar.setSelectedNavigationItem(arg0);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO 自動產生的方法 Stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO 自動產生的方法 Stub
}
});
Log.w("Step7","inviewPager");
Log.w("Step8","inviewPager");
return v;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO 自動產生的方法 Stub
}
class MyAdapter extends FragmentPagerAdapter
{
public MyAdapter(FragmentManager fm) {
super(fm);
Log.w("in","Fragment-2");
}
#Override
public Fragment getItem(int arg0) {
// TODO 自動產生的方法 Stub
Log.w("in","Fragment-1");
Fragment fragment = null;
Log.w("in","Fragment000");
if(arg0==0)
{
Log.w("in","FragmentA");
fragment = new FragmentA();
}
if(arg0==1)
{
Log.w("in","FragmentB");
fragment = new FragmentB();
}
return fragment;
}
#Override
public int getCount() {
// TODO 自動產生的方法 Stub
return 2;
}
}
#Override
public void onStop() {
super.onPause();
Log.w("in","inStop");
}
#Override
public void onPause() {
super.onPause();
getActivity().getActionBar().removeAllTabs();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
Log.w("in","onPause");
onDetach();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.w("in","onDestroy");
}
#Override
public void onResume() {
super.onResume();
Log.w("in","onResume");
}
#Override
public void onStart() {
Log.w("Step3","inviewPager");
actionBar = getActivity().getActionBar();
Log.w("Step4","inviewPager");
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Log.w("Step5","inviewPager");
tab1=actionBar.newTab();
tab2=actionBar.newTab();
Log.w("Step6","inviewPager");
tab1.setText("Tab 1");
tab1.setTabListener(this);
tab2.setText("Tab 2");
tab2.setTabListener(this);
actionBar.addTab(tab1);
Log.w("in","onStart2");
actionBar.addTab(tab2);
super.onStart();
}
}
From my FragmentActivity, i want to update my ListView of a Fragment(created by code) at onRestart of the FragmentActivity. There is no fragment and tag in XML file. Here is my FragmentActivity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new ProfilePagerAdapter(getSupportFragmentManager(),
myFriendsList, notifiedFriendsList);
viewPager.setAdapter(mAdapter);
..........
my FragmentPagerAdapter is
public class ProfilePagerAdapter extends FragmentPagerAdapter {
private ArrayList<Friend> myFriends;
private ArrayList<ExpandableChild> notifiedFriendsList;
private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ProfilePagerAdapter(FragmentManager fm, ArrayList<Friend> myFriends, ArrayList<ExpandableChild> notifiedFriendsList) {
super(fm);
// TODO Auto-generated constructor stub
this.myFriends = myFriends;
this.notifiedFriendsList = notifiedFriendsList;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new FriendsFragment(myFriends);
case 1:
return new MyProfileFragment(notifiedFriendsList);
}
return null;
}
#Override
public int getCount() {
return 2;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
In my FriendsFragment class, i have a ListView. I used following two methods to update the ListView from my FragmentActivity in the class.
public void setNewFriendList(ArrayList<Friend> myFriends){
this.friendsList = myFriends;
}
public void updateList(){
adapter.notifyDataSetChanged();
}
Now i want to update the ListView of FriendsFragment at onRestart() of FragmentActivity in following way.
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
android.support.v4.app.Fragment frag = mAdapter
.getRegisteredFragment(0);
if (frag != null) {
((FriendsFragment) frag).setNewFriendList(myFriendsList);
((FriendsFragment) frag).updateList();
Toast.makeText(UserProfileTab.this, "Updated",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(UserProfileTab.this, "Not Updated:",Toast.LENGTH_LONG).show();
}
}
But in Toast shows Not Updated as frag returns null. I followed link1 and link1. Thanks in advance.
I would like to create a new fragment every time when I click its tab.
I tried to get the tab and to create a fragment. But it doesn't seem to work.
Here is my code.
Main Activity
public class MainActivity extends FragmentActivity {
private static ViewPager viewPager;
private static TabsPagerAdapter mAdapter;
private static ActionBar actionBar;
// Tab titles
private String[] tabs = { "TopRated", "Hots", "NEW"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
//actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(tabListener));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
static ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
};
TabsPagerAdapter
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new TopRatedFragment();
case 1:
return new HotStoryFragment();
case 2:
return new AllClassFragment();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
One of the fragments
public class HotStoryFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Refresh_F","(2) HotStory");
View rootView = inflater.inflate(R.layout.fragment_hotstory, container, false);
TextView tvStudy = (TextView)rootView.findViewById(R.id.text);
return rootView;
}
I have a parent SherlockFragmentActivity class that contains ViewPager with 4 Fragments inside.
One of them extends from SherlockListFragment and I want to scroll it to top by click on it's tab.
MainActivity class:
public class MainActivity extends SherlockFragmentActivity {
ViewPager viewPager;
TabAdapter tabAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
setTheme(Constants.THEME);
viewPager = new ViewPager(this);
viewPager.setId(R.id.pager);
viewPager.setBackgroundResource(R.color.background_color);
tabAdapter = new TabAdapter(this,viewPager);
super.onCreate(savedInstanceState);
setContentView(viewPager);
// Action bar setup
setupTabs(savedInstanceState);
}
private void setupTabs(Bundle savedInstanceState) {
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i = 1; i <= 4; i++) {
ActionBar.Tab tab = getSupportActionBar().newTab();
switch (i) {
case 1:
tab.setText(R.string.feed).setTabListener(tabAdapter);
tabAdapter.addTab(EventListFragment.class);
break;
case 2:
tab.setText(R.string.downloads).setTabListener(tabAdapter);
tabAdapter.addTab(LocalEventListFragment.class);
break;
case 3:
tab.setText(R.string.tags).setTabListener(tabAdapter);
tabAdapter.addTab(TagsFragment.class);
break;
case 4:
tab.setText(R.string.settings).setTabListener(tabAdapter);
tabAdapter.addTab(SettingsFragment.class);
break;
}
getSupportActionBar().addTab(tab);
}
}
TabAdapter class:
public static class TabAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
private final Context mContext;
private final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
private final ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
private final ActionBar mActionBar;
private final ViewPager mViewPager;
public TabAdapter(SherlockFragmentActivity activity, ViewPager pager){
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(Class<?> clss){
classes.add(clss);
mFragments.add(Fragment.instantiate(mContext, clss.getName(),
null));
}
#Override
public Fragment getItem(int i) {
return mFragments.get(i);
}
public int getId(int index){
return mFragments.get(index).getId();
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// fixed double call onTabReselected
if (mActionBar.getSelectedNavigationIndex() != position)
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int i) {
}
#Override
public int getCount() {
return 4;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
final int position = tab.getPosition();
final Fragment fragment = mFragments.get(position);
if (fragment != null) {
switch (position) {
case 0:
// call tab's ListFragment scroll to top item
((EventListFragment) fragment).scrollToTop();
break;
case 1:
// do something
break;
}
}
}
onTabReselected called, then user press current tab, so I try to do EventListFragment scrolling:
EventListFragment class:
public class EventListFragment extends SherlockListFragment {
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mAdapter = new EventListAdapter(getSherlockActivity());
setListAdapter(mAdapter);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
#Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View eventListLayout = inflater.inflate(R.layout.eventlist_fragment,null);
ListView lv = (ListView) eventListLayout.findViewById(android.R.id.list);
ViewGroup parent = (ViewGroup) lv.getParent();
//Remove ListView and add PullToRefreshListView in its place
int lvIndex = parent.indexOfChild(lv);
parent.removeViewAt(lvIndex);
mPullToRefreshListView = onCreatePullToRefreshListView(inflater, savedInstanceState);
parent.addView(mPullToRefreshListView, lvIndex, lv.getLayoutParams());
return eventListLayout;
}
public void scrollToTop() {
if (getSherlockActivity() != null) { // null after screen rotation
final ListView listView = getListView();
listView.post(new Runnable(){
public void run() {
listView.smoothScrollToPosition(0);
}});
}
}
It works on application start, but after screen rotation scrollToTop - getSherlockActivity() returns null.
If remove this condition check, have an exception:
java.lang.IllegalStateException: Content view not yet created
at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
at com.project.fragment.EventListFragment.scrollToTop(EventListFragment.java:337)
at com.project.MainActivity$TabAdapter.onTabReselected(MainActivity.java:411)
at com.actionbarsherlock.internal.app.ActionBarWrapper$TabWrapper.onTabReselected(ActionBarWrapper.java:327)
I haven't totally understatinding how to ViewPager and its FragmentPagerAdapter works. So can't find a problem, that occurs.
Use this FragmentPageAdapter:
public class TestFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[] { "CATEGORIAS", "PRINCIPAL", "AS MELHORES", };
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar,
R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms,
};
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {Fragment f = null;
switch(position){
case 0:
{
f = new ArrayListFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 1:
{
f = new HomeFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 2:
{
f = new EndlessCustomView();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
default:
throw new IllegalArgumentException("not this many fragments: " + position);
}
return f;
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return TestFragmentAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
This Activity:
public class BaseSampleActivity extends SlidingFragmentActivity {
private static final Random RANDOM = new Random();
TestFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
protected ListFragment mFrag;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.themed_titles);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(1);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
Applied solution according to this post:
MainActivity class:
//...
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
FragmentManager manager = getSupportFragmentManager();
for (int i = 0; i < tabAdapter.getClasses().size(); i++) {
String className = tabAdapter.getClasses().get(i).getName();
if (manager.findFragmentByTag(className) != null) {
manager.putFragment(outState, className, manager.findFragmentByTag(className));
}
}
}
//...
TabAdapter class:
//...
public void addTab(Class<?> clss, FragmentManager manager, Bundle savedInstanceState) {
classes.add(clss);
String className = clss.getName();
tags.add(className);
Fragment fragment;
if (savedInstanceState != null) {
fragment = manager.getFragment(savedInstanceState, className);
if (fragment == null) {
fragment = createFragment(className);
manager.beginTransaction().add(fragment, className);
}
} else {
fragment = createFragment(className);
manager.beginTransaction().add(fragment, className);
}
mFragments.add(fragment);
}
//...
where createFragment is a simple method, that creates needed fragment by passed class name.