Skip to content Skip to sidebar Skip to footer

Actionbar And Fragments On Ics 4.0.3

I'm trying to develop an Android app and I have some problems with the ActionBar. I need something similar to Instagram or Twitter for Android: I have an Action Bar with 3 tabs and

Solution 1:

Use the method detach and attach wherever necessary on the fragment on changing the tab. For example,

publicvoidonTabSelected(Tab tab, FragmentTransaction ft) {
        if (mFragment == null) {
            mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
            ft.add(android.R.id.content, mFragment, mTag);
        } else {
            ft.attach(mFragment);
        }
    }

You can see the full source in Android samples in the following path android-sdk -> samples -> android-16 -> ApiDemos -> src -> com -> example -> android -> apis -> app -> FragmentTabs.java

Solution 2:

In your Tab1Fragment in onClick method you replace mFragment instance with newly created nuovo

Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.

(It looks like mFragment now reffer to another object(nuovo), but i may be wrong -- I'll check it tommorow)

So, at first replace this line transaction.replace(android.R.id.content, nuovo);

with

transaction.replace(android.R.id.content, nuovo, "nuovoTag");

Then modify your public void onTabSelected(Tab tab, FragmentTransaction ft) with the following code:

Fragment fr = getFragmentManager().findFragmentByTag("nuovoTag");
if (fr != null)
  ft.remove(fr);

  if (mFragment == null) {
      mFragment = Fragment.instantiate(mActivity, mClass.getName());
      ft.add(android.R.id.content, mFragment, mTag);
  } else {
      ft.attach(mFragment);
  }

Post a Comment for "Actionbar And Fragments On Ics 4.0.3"