简体   繁体   中英

using actionbar tabs to switch between fragments

A week later, I am still trying without success to create a tabbed action bar with v7 support to be able to switch between fragments. This is my first effort at an android app in native code and I am new to Java.

My Main.Activity.java looks like this

package com.example.appcompattest;

import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;


public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main);
    // setup action bar for tabs
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayShowTitleEnabled(true);

    Tab tab = actionBar.newTab()
                       .setText(R.string.grammar)
                       .setTabListener(new TabListener<GrammarFragment>(
                               this, "GRAMMAR", GrammarFragment.class));
    actionBar.addTab(tab);

    tab = actionBar.newTab()
                   .setText(R.string.lexis)
                   .setTabListener(new TabListener<LexisFragment>(
                           this, "LEXIS", LexisFragment.class));
    actionBar.addTab(tab);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}


public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
    private Fragment mFragment;
    private final Activity mActivity;
    private final String mTag;
    private final Class<T> mClass;

    /** Constructor used each time a new tab is created.
      * @param activity  The host Activity, used to instantiate the fragment
      * @param tag  The identifier tag for the fragment
      * @param clz  The fragment's Class, used to instantiate the fragment
      */

    public TabListener(Activity activity, String tag, Class<T> clz) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
    }

    /* The following are each of the ActionBar.TabListener call backs */
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // Check if the fragment is already initialized
        if (mFragment == null) {
            // If not, instantiate and add it to the activity
            mFragment = Fragment.instantiate(mActivity, mClass.getName());
            // Commit the transaction
            ft.add(R.id.fragment_holder, mFragment, mTag);
        } else {
            // If it exists, simply attach it in order to show it
            ft.attach( mFragment);
        }
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        if (mFragment != null) {
            // Detach the fragment, because another one is being attached
            ft.detach(mFragment);
        }
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // User selected the already selected tab. Usually do nothing.
    }
}

}

Apart from this, I have a Framelayout called fragment_holder in my activity_main.xml to swap the tabs in and out of, and separate xml files for my two fragments. I also have two classes, LexisFragment.java and GrammarFragment.java which are basically the same (with Grammar/grammar substituted for Lexis/lexis) and look like this.

public class LexisFragment extends Fragment {
    @Override   
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.lexisfragment, container, false);
    }

When I run the activity, the first fragment is added. Selecting the other tab causes the the second fragment to be added but without destroying the first. On subsequent tab changes the fragments just remain superimposed.

After logging the variables (mTag and mFragment) at each step and experimenting with ft.remove(), I am pretty sure that what is happening is as follows: On the first tab change onTabUnselected fails to detach / remove anything while onTabSelected adds the new fragment. Then, on sucessive tab changes, the tab which should be added is removed while the tab which should be removed is added. I am grateful for any suggestions.

Hope this helps you..

public class AboutActivity extends Activity {
boolean mIsFromMem;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mIsFromMem=savedInstanceState!=null;
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM