Skip to content

Instantly share code, notes, and snippets.

@umanda
Created August 15, 2016 06:07
Show Gist options
  • Save umanda/c40cfbd088146b0297b311646c541726 to your computer and use it in GitHub Desktop.
Save umanda/c40cfbd088146b0297b311646c541726 to your computer and use it in GitHub Desktop.
Refresh/Reload/Re instantiate a Fragment in an android tab system
// In Activity:
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 0) {
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
Intent i = new Intent("TAG_REFRESH");
lbm.sendBroadcast(i);
}
}
// And your Fragment:
public class MyFragment extends Fragment {
MyReceiver r;
public void refresh() {
//yout code in refresh.
Log.i("Refresh", "YES");
}
public void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(context).unregisterReceiver(r);
}
public void onResume() {
super.onResume();
r = new MyReceiver();
LocalBroadcastManager.getInstance(context).registerReceiver(r,
new IntentFilter("TAG_REFRESH"));
}
private class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MyFragment.this.refresh();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment