I have a MainActivity which contains a tab bar with two fragments: MainFragment and WishlistFragment. They both extend as ListFragment.
When someone touches a menu item from the Option menu, I want the ListView within the Fragment that is showing to refresh its list using its custom adapter called LazyAdapter adapter.
So in here is where I want the refresh to go in my MainActivity code:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_edit:
// find out which fragment is showing here
// refresh the fragment's listview here
// adapter.notifyDataSetChanged();
return true;
}
}
How can I do this? I am not sure how to call forward into the fragment and how to determine which fragment is showing.
Here is how I have my tabs set up in MainActivity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar.addTab(actionBar.newTab().setText("Main").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Wishlist").setTabListener(this));
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the container
ListFragment newfragment = null;
switch (tab.getPosition() + 1)
{
case 1:
newfragment = new MainFragment();
break;
case 2:
newfragment = new WishlistFragment();
break;
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, newfragment)
.commit();
}
Step #1: Fix your implementation of
onTabSelected(). You do not want to be creating a new fragment each time the user chooses a tab. Instead, you want to have two fragments, held onto by the activity in data members, and use those in thereplace()transaction.Step #2: When needed, call
getSelectedNavigationIndex()on theActionBar, use that to choose which of the two fragments you need (obtained from the data members mentioned in Step #1 above), and call some method on the fragment to do what you want.