Search code examples
androidcallbackandroid-fragmentsandroid-listfragmentandroid-actionbar-compat

Android: Determine selected actionbar tab in Fragment


I'm working on a project in which I have data to display in a list view. My data has six categories which is identified by a text field in the database containing the numbers 0 - 5. I have created an Action Bar with tab navigation enabled. I have tabs for all items and each of the 6 six categories for a total of 7 tabs.

I have created a ListFragment to display the data. I created an instance of the ListFragment for each tab and change tabs via the tab listener. I would like to filter the data by the category and I need a way to determine which tab instantiated the ListFragment.

What is the best way to pass the category to the ListFragment??

Here is my MainActivity:

public class MainActivity extends ActionBarActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Initialize action bar
    final ActionBar actionBar = getSupportActionBar();

    // set action bar defaults
    actionBar.setDisplayHomeAsUpEnabled(false);
    actionBar.setDisplayUseLogoEnabled(true);;
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // set up action bar tabs
    Tab AllTab = actionBar.newTab().setText("All Items");
    Tab Cat0Tab = actionBar.newTab().setText("Category 0");
    Tab Cat1Tab = actionBar.newTab().setText("Category 1");
    Tab Cat2Tab = actionBar.newTab().setText("Category 2");
    Tab Cat3Tab = actionBar.newTab().setText("Category 3");
    Tab Cat4Tab = actionBar.newTab().setText("category 4");
    Tab Cat5Tab = actionBar.newTab().setText("Category 5");                     

    // create the fragments for each tab
    ListFragment allFragment = new ItemListFragment();
    ListFragment cat0Fragment = new ItemListFragment(); 
    ListFragment cat1Fragment = new ItemListFragment();
    ListFragment cat2Fragment = new ItemListFragment();
    ListFragment cat3Fragment = new ItemListFragment();
    ListFragment cat4Fragment = new ItemListFragment();
    ListFragment cat5Fragment = new ItemListFragment();

    // set the tab listener for each tab
    AllTab.setTabListener(new MyTabsListener(allFragment));
    Cat0Tab.setTabListener(new MyTabsListener(cat0Fragment));
    Cat1Tab.setTabListener(new MyTabsListener(cat1Fragment));
    Cat2Tab.setTabListener(new MyTabsListener(cat2Fragment));
    Cat3Tab.setTabListener(new MyTabsListener(cat3Fragment));
    Cat4Tab.setTabListener(new MyTabsListener(cat4Fragment));
    Cat5Tab.setTabListener(new MyTabsListener(cat5Fragment));       

    // Add tabs to action bar
    actionBar.addTab(AllTab);
    actionBar.addTab(Cat0Tab);
    actionBar.addTab(Cat1Tab);
    actionBar.addTab(Cat2Tab);
    actionBar.addTab(Cat3Tab);
    actionBar.addTab(Cat4Tab);
    actionBar.addTab(Cat5Tab);

    if (savedInstanceState != null) {
        actionBar.setSelectedNavigationItem(savedInstanceState.getInt("tabState"));
    }   
}   

class MyTabsListener implements ActionBar.TabListener {
    private Fragment fragment;

    public MyTabsListener(ListFragment fragment) {
        this.fragment = fragment;
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        ft.replace(android.R.id.content, fragment);;    
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {

        if (fragment != null) {
            FragmentManager fm = getSupportFragmentManager();
            if (fm.getBackStackEntryCount()>0) {
                fm.popBackStack(fm.getBackStackEntryAt(0).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
            ft.remove(fragment);
        }           
    }

    @Override
    public void onTabReselected(Tab tab,FragmentTransaction ft) {
        // TODO Auto-generated method stub      
    }       
}

Here is the onActivityCreated method from ItemsListFragment class:

    @Override
public void onActivityCreated(Bundle savedState) {
    super.onActivityCreated(savedState);

    mActivity = getActivity();
    db = new DataAdapter(mActivity);
    db.open();      

    // Get all of the records from the database and create the materials ListAdapter
    switch(Integer.parseInt(mTag)) {
    case 6:
        cursor = db.getAllRecords();
        break;
    default:
        cursor = db.getRecordCat(mTag);
        break;
    }

    String[] from = new String[] { DataAdapter.KEY_TITLE };
    int[] to = new int[] {R.id.item_title }; 


    // Now create an array adapter and set it to display using our row
    items = new MyListAdapter(getActivity(), R.layout.item_cell, cursor, from, to);


    // get the listview
    ListView listview = getListView();
    listview.setAdapter(items);
}

I've tried creating and attaching arguments to each fragment but it always returns the number for the last fragment created. I've looked into call backs, but I'm uncertain how to proceeds as the value is dynamic depending on which tab was selected.

Any thoughts or suggestions will be appreciated.


Solution

  • I think the best way to make each fragment aware of its number is to pass the number as an argument to the constructor of the fragment.