Reputation: 650
I have two fragments, declared in separate classes - AFragment and BFragment. My MainActivity looks somewhat like this:
public class MainActivity extends SherlockFragmentActivity implements ActionBar.TabListener
{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab firstTab = getSupportActionBar().newTab().setText("Fragment A");
ActionBar.Tab secondTab = getSupportActionBar().newTab().setText("Fragment B");
SherlockFragment firstFragment = new AFragment();
SherlockFragment secondFragment = new BFragment();
firstTab.setTabListener(this);
secondTab.setTabListener(this);
getSupportActionBar().addTab(firstTab);
getSupportActionBar().addTab(secondTab);
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition())
{
case 0:
ft.replace(R.id.fragment_container, new AFragment());
break;
case 1:
ft.replace(R.id.fragment_container, new BFragment());
break;
}
Toast.makeText(this, tab.getText(), Toast.LENGTH_LONG).show();
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
My question is, how do I pass a variable - say an integer - between my two fragments? For example, I'd press a button in the first fragment, and a particular integer would appear in a TextView in the second one.
Upvotes: 2
Views: 3972
Reputation: 83313
Fragments are meant to be re-used... that is, two fragments should not directly pass data between each other. Instead, you should define a callback method in the Activity. This will ensure that you can re-use your fragments elsewhere in your app (and in other apps you make) if you need to.
Upvotes: 2