aha
aha

Reputation: 3759

Overlaid widgets in fragments after orientation change

In my Android app I'm using an Action Bar with tabs to switch between fragments that display the content of the tabs. Everything is working fine until an orientation change: Then Android starts to draw the widgets on top of each other so that the contents of the fragments get mixed up. My TabListener:

private class TabListener implements ActionBar.TabListener {
    private final Activity mActivity;
    private final String mTag;

    public TabListener(Activity activity, String tag) {
        mActivity = activity;
        mTag = tag;
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        Fragment mFragment = MyActivity.this.getSupportFragmentManager().findFragmentByTag(mTag);
        if (mFragment == null) {
            mFragment = new MyFragment();
            ft.add(android.R.id.content, mFragment, mTag);
        } else {
            ft.attach(mFragment);
        }
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
        Fragment mFragment = MyActivity.this.getSupportFragmentManager().findFragmentByTag(mTag);
        if (mFragment != null) {
            ft.detach(mFragment);
        }
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
        // Do nothing
    }
}

The only thing I noticed was that on every orientation change, onTabUnselected() won't be called, but still onTabSelected() is called (so the current tab will be attached twice without being detached in between). If that's the problem, I do not know how to fix it. If that's not the problem, I do not know where to look. I would be glad if someone has a suggestion.

Sidenote: I'm using the Action Bar from ActionBarSherlock. The problem appears on all Android versions I tested with (2.3, 4.0, 4.1).

Upvotes: 2

Views: 499

Answers (1)

MGDroid
MGDroid

Reputation: 1659

I am not sure but here are some steps you can follow

  • Take Bundle reference before your Activity onCreate() method.

    Bundle b1;

  • In your onCreate() method , put the Bundle value in b1

    @Override
    public void onCreate(Bundle savedInstanceState) {b1=savedInstanceState;
    

    ............................ }

  • Use this b1 in your onTabSelected method as

    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        Fragment mFragment = MyActivity.this.getSupportFragmentManager().findFragmentByTag(mTag);
    
    
     if (b1!=null){
     ft.detach(mFragment);
    

//and the rest code

   ................}
        }

Its an conclusion , which I have concluded with my working with fragments, but I have not done it with TabListener. So tell me when you are done , or any other solution.

Upvotes: 1

Related Questions