Search code examples
androidandroid-fragmentsactionbarsherlockotto

Communicative Between Fragments on Android


I am attempting to build an Android application that has two tabs, one for a textField/button and TreeMenu (where each element has a checkbox associated with it) and another for a list. I am also using an ActionBarSherlock. I have already successfully written the program in a single main activity, but am having difficulty figuring out how to divide this original activity to correspond with the two new fragment instances I need to create for each tab. Moreover, each time an item is added in the first tab (whether it is from being checked off or added to the textField), the list in the second window ought to recognize the update.

To build the action bar I can do this...

ActionBar actionbar = getSupportActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.setTitle("AppName");

To create the tabs..

 ActionBar.Tab Frag1Tab = actionbar.newTab().setText("InputTab");
 ActionBar.Tab Frag2Tab = actionbar.newTab().setText("ListTab");

To create the fragments and its listeners underlying each tab...

Fragment Fragment1 = new Fragment_1();
Fragment Fragment2 = new Fragment_2();
Frag1Tab.setTabListener(new MyTabsListener(Fragment1));
Frag2Tab.setTabListener(new MyTabsListener(Fragment2));

To add them to the action bar...

actionbar.addTab(Frag1Tab);
actionbar.addTab(Frag2Tab);

All of this appears within my MainActivity. I want, for example, an ArrayList variable to be accessible to both Fragments so, like I said, I can update the list. I would love to hear any help you can provide. I would be interested to see how the Otto API could work for something like this, but I am not picky!


Solution

  • A singleton class could help solve your problem.

    public class GlobalApp {
        private static GlobalApp instance = new GlobalApp();
    
        private GlobalApp() {}
    
        public static GlobalApp getInstance() {
            return instance;
        }
    
        public ArrayList < ClassName > varName = new ArrayList < ClassName > ();
    
    }
    

    Then use in your class like this..

    GlobalApp.getInstance().varName