Fragment is re created when ActionbarSherlock tab is selected - android

I have a Fragment Activity which holds three fragments.
public class MainActivity extends SherlockFragmentActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = bar.newTab();
ActionBar.Tab tab2 = bar.newTab();
ActionBar.Tab tab3 = bar.newTab();
tab1.setText("");
tab1.setIcon(R.drawable.abs__ic_menu_share_holo_dark);
tab2.setText("");
tab2.setIcon(R.drawable.abs__ic_voice_search);
tab3.setText("");
tab3.setIcon(R.drawable.abs__ic_cab_done_holo_dark);
if (savedInstanceState == null) {
tab1.setTabListener(new MyTabListener());
tab2.setTabListener(new MyTabListener());
tab3.setTabListener(new MyTabListener());
bar.addTab(tab1);
bar.addTab(tab2);
bar.addTab(tab3);
}
}
private class MyTabListener implements ActionBar.TabListener {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()) {
case 0:
FeedsActivity frag = new FeedsActivity();
ft.replace(android.R.id.content, frag);
return;
case 1:
ProfileActivity frag2 = new ProfileActivity();
ft.replace(android.R.id.content, frag2);
return;
case 2:
MyMemoirsActivity frag3 = new MyMemoirsActivity();
ft.replace(android.R.id.content, frag3);
return;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
}
And here is first Fragment,
public class FeedsActivity extends SherlockFragment {
public static String[] MainCategory;
public static String[] MainCategoryId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group,
Bundle saved) {
setRetainInstance(true);
return inflater.inflate(R.layout.activity_feeds, group, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new GetMainCategory(getActivity()).execute();
}
}
When I select second tab and then select first tab the async task in first fragment is called again.How can I retain state of first fragment so that its view is created once? I have used setRetainInstance(true) but didnt work.

I solved this issue by using show and hide instead of attach and detach.
private class MyTabListener implements ActionBar.TabListener {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()) {
case 0:
if (frag1 == null) {
// If not, instantiate and add it to the activity
frag1 = Fragment.instantiate(getApplicationContext(),
FeedsActivity.class.getName());
ft.add(android.R.id.content, frag1, "Feeds");
} else {
// If it exists, simply attach it in order to show it
ft.show(frag1);
}
return;
case 1:
if (frag2 == null) {
// If not, instantiate and add it to the activity
frag2 = Fragment.instantiate(getApplicationContext(),
ProfileActivity.class.getName());
ft.add(android.R.id.content, frag2, "Profile");
} else {
// If it exists, simply attach it in order to show it
ft.show(frag2);
}
return;
case 2:
if (frag3 == null) {
// If not, instantiate and add it to the activity
frag3 = Fragment.instantiate(getApplicationContext(),
History.class.getName());
ft.add(android.R.id.content, frag3, "History");
} else {
// If it exists, simply attach it in order to show it
ft.show(frag3);
}
return;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if (frag1 != null) {
// Detach the fragment, because another one is being attached
switch (tab.getPosition()) {
case 0:
ft.hide(frag1);
return;
case 1:
ft.hide(frag2);
return;
case 2:
ft.hide(frag3);
return;
}
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}

The proper way to use TabListener is this :
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
#override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
Basically you need to check if that's the first time when your Fragment is being initialised. If not, you should add it to your screen and when the user unselect a tab you should detach the current visible fragment and add the new one. That's the way it should work. You don't need to create a new instance of Fragment everytime user click the tab.

Related

Using unknown number of tabs

I want to create an activity that can display any number of tabs, without creating an activity for each tab.
Is it possible?
The only way I saw creating tabs included creating an activity for each one.
You can try as follows ,
Extend your activity from ActionBarActivity and add required number of tabs programmatically ,
ActionBar.TabListener tabListener;
mactionBar = getActionBar();
mactionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tabListener=new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
displayTabs(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
displayTabs(tab.getPosition());
}
};
mactionBar.addTab(mactionBar.newTab().setText(<any text>).setTabListener(tabListener));
//call the same method for required number of tabs
Call the same fragment for each tab click
private void displayTabs(int position)
{
Fragment fragment = null;
switch (position) {
case 0:
fragment = new YourFragment();
break;
case 1:
fragment = new YourFragment();
break;
// same for required numder of cases
default:
break;
}
if (fragment != null)
{
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(<container id>, fragment).commit();
}
}

Sherlock tabs not working on orientation change

I managet to set up three tabs using Sherlock ActionBar. The only problem is that when orientation is changed, tabs can not be tapped any more. It seem like the onTabSelected() is not called. Example: I am in portrait and the tab2 is selected. I change into lanscape. Tab2 is still selected, I tap tab3 but nothing happens. Then when I go back to portrait again, tab3 is shown. I am testing in Android 2.3.6.
This is the main activity:
public class Activity_Main extends SherlockFragmentActivity {
ActionBar.Tab tab1, tab2, tab3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTabs();
}
void setTabs(){
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
tab1 = actionBar.newTab();
tab2 = actionBar.newTab();
tab3 = actionBar.newTab();
tab1.setText("Week");
tab2.setText("Today");
tab3.setText("ToDo");
tab1.setTabListener(new TabListener<Fragment_Start_Week>(this, "week", Fragment_Start_Week.class));
tab2.setTabListener(new TabListener<Fragment_Start_Today>(this, "today", Fragment_Start_Today.class));
tab3.setTabListener(new TabListener<Fragment_Start_Todo>(this, "todo", Fragment_Start_Todo.class));
}
private class TabListener<T extends SherlockFragment> implements com.actionbarsherlock.app.ActionBar.TabListener{
private SherlockFragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
/**
* Constructor used each time a new tab is created.
*
* #param activity
* The host Activity, used to instantiate the fragment
* #param tag
* The identifier tag for the fragment
* #param clz
* The fragment's Class, used to instantiate the fragment
*/
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab, FragmentTransaction ft) {
SherlockFragment preInitializedFragment = (SherlockFragment) ((FragmentActivity) mActivity).getSupportFragmentManager().findFragmentByTag(mTag);
// Check if the fragment is already initialized
if (mFragment == null && preInitializedFragment == null) {
// If not, instantiate and add it to the activity
mFragment = (SherlockFragment) SherlockFragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else if (mFragment != null) {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
} else if (preInitializedFragment != null) {
ft.attach(preInitializedFragment);
mFragment = preInitializedFragment;
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}
This is a fragment:
public class Fragment_Start_Week extends SherlockFragment implements OnClickListener{
void create_table() {
...
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved)
{
return inflater.inflate(R.layout.fragment_start_week, group, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
create_table();
}
#Override
public void onClick(View view) {
...
}
}
TIA
After a lot of trial and errors I've found the following solution for this bug:
#Override
public void onConfigurationChanged(Configuration newConfig) {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
super.onConfigurationChanged(newConfig);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}
The trick is to change the navigation mode to list then change back to tabs.

Unable to start activity componentInfo Tablistener suddenly crashing the app

So i'm getting this annoying problem. I'm pretty noob when it comes to android, so any help would be nice.
This is my MainActivity which seems to be crashing according to LogCat.
The app i'm trying to create must pull data from XML data, which i'm trying to get. Then from this data it must set the tabs name (that's what i'm trying to do).
public class MainActivity extends SherlockActivity {
private String uniqeAppId;
private ArrayList<StartupInfo> info;
private String ChannelTab;
private String VicinityTab;
private String CustomTab;
private String TrackingTab;
private String MoreTab;
public static Context appContext;
private DownloadXmlTask downloadxml = new DownloadXmlTask(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info = new ArrayList<StartupInfo>();
downloadxml.loadPage();
appContext = getApplicationContext();
ActionBar actionbar = getSupportActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionbar.setTitle(uniqeAppId);
ActionBar.Tab Frag1 = actionbar.newTab().setText(ChannelTab);
ActionBar.Tab Frag2 = actionbar.newTab().setText(VicinityTab);
ActionBar.Tab Frag3 = actionbar.newTab().setText(CustomTab);
ActionBar.Tab Frag4 = actionbar.newTab().setText(TrackingTab);
ActionBar.Tab Frag5 = actionbar.newTab().setText(MoreTab);
Fragment Fragment1 = new Channeltab();
Fragment Fragment2 = new Vicinitytab();
Fragment Fragment3 = new Customtab();
Fragment Fragment4 = new Trackingtab();
Fragment Fragment5 = new Moretab();
Frag1.setTabListener(new MyTabListener(Fragment1));
Frag2.setTabListener(new MyTabListener(Fragment2));
Frag3.setTabListener(new MyTabListener(Fragment3));
Frag4.setTabListener(new MyTabListener(Fragment4));
Frag5.setTabListener(new MyTabListener(Fragment5));
actionbar.addTab(Frag1);
actionbar.addTab(Frag2);
actionbar.addTab(Frag3);
actionbar.addTab(Frag4);
actionbar.addTab(Frag5);
}
public void GetTextForTabs(ArrayList<StartupInfo> info2) {
this.info = info2;
StartupInfo info3 = info.get(0);
this.ChannelTab = info3.getChannelTab();
this.VicinityTab = info3.getVicinityTab();
this.CustomTab = info3.getCustomTab();
this.TrackingTab = info3.getTrackingTab();
this.MoreTab = info3.getMoreTab();
}
#Override
public void onStart() {
super.onStart();
}
public void setInfo(ArrayList<StartupInfo> info) {
this.info = info;
}
public void alert(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
public class MyTabListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}
Then the LogCat:
It seems to be the TabListener. But I don't understand why. It wasn't doing that earlier. It was when i tried to add data it started to crash. Can anyone help me here ?
You have a null pointer exception at line 111 of your activity (in onTabSelected). It looks as though the null reference is probably to "fragment". Look at the section on "Performing fragment transactions":
http://developer.android.com/guide/components/fragments.html
This code will not fit your program exactly, but it gives you the general idea. You need to begin, do your add/replace/why and then commit.
By the by, since you are using ActionBarSherlock why not use the Support library so as to be able to support older versions of Android ?
Here is a simple example (it contains some superfluous stuff that you don't need) that might help:
public class ExtraContent extends SherlockFragmentActivity {
// Declare Tab Variable
com.actionbarsherlock.app.ActionBar.Tab tab;
boolean mDebugLog = false;
String mDebugTag="ian_";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//mDebugLog = true;
debugLog("ExtraContent onCreate" );
// Create the actionbar
com.actionbarsherlock.app.ActionBar bar = getSupportActionBar();
// Show Actionbar Home Icon (as normal)
bar.setDisplayShowHomeEnabled(true);
// Show Actionbar Title (as normal)
bar.setDisplayShowTitleEnabled(true);
// Create Actionbar Tabs
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//enable home ...
bar.setDisplayHomeAsUpEnabled(true); // ?
bar.setHomeButtonEnabled(true); // this is the one that enables home navigation
//ib18 view for fragments ...
setContentView(R.layout.extra_content);
//create the fragment we want to use for display content
Fragment ExtraLogin = new ExtraLogIn();
// Create First Tab
ActionBar.Tab tab0 = bar.newTab();
tab0 = bar.newTab();
tab0.setText("Unlock");
tab0.setTabListener(new TabListener<ExtraTab0>(this, "tab0",ExtraTab0.class, null));
bar.addTab(tab0);
// Create Second Tab
ActionBar.Tab tab1 = bar.newTab();
tab1 = bar.newTab();
tab1.setText("Level 1");
tab1.setTabListener(new TabListener<ExtraTab1>(this, "tab1",ExtraTab1.class, null));
bar.addTab(tab1);
// Create Third Tab
ActionBar.Tab tab2 = bar.newTab();
tab2 = bar.newTab();
tab2.setText("Level 2");
tab2.setTabListener(new TabListener<ExtraTab2>(this, "tab2",ExtraTab2.class, null));
bar.addTab(tab2);
if (savedInstanceState != null) { //if there is a saved bundle use it ...
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
else {
//ib18 savedInstanceState null so fti so start Login frag ...
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.fb, ExtraLogin, "ExtraLogin").commit();
}
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
debugLog("ExtraContent onMenuItemSelected" );
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, QuizLaunch.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
debugLog("ExtraContent onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putInt("tab", getSupportActionBar().getSelectedNavigationIndex());
}
public class TabListener<T extends Fragment> implements ActionBar.TabListener{
private final FragmentActivity mActivity;
private final String mTag;
private final Class<T> mClass;
private final Bundle mArgs;
private Fragment mFragment;
public TabListener (FragmentActivity activity, String tag, Class<T> clz,
Bundle args) {
mActivity = activity;
mTag = tag;
mClass = clz;
mArgs = args;
debugLog("ExtraContent TabListener" );
FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
// Check to see if we already have a fragment for this tab, probably
// from a previously saved state. If so, deactivate it, because our
// initial state is that a tab isn't shown.
mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
//
if (mFragment != null && !mFragment.isDetached()) {
ft.detach(mFragment);
}
ft.commit();
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
debugLog("ExtraContent onTabSelected");
ft = mActivity.getSupportFragmentManager()
.beginTransaction();
if (mFragment == null) {
mFragment = Fragment.instantiate(mActivity, mClass.getName(),mArgs);
debugLog("adding fragment "+mTag );
ft.add(R.id.tab, mFragment, mTag); //ib18 add to "tab" holder
ft.show(mFragment); //ib1.6 show fragment ...
ft.commit();
} else {
debugLog("attaching fragment "+mTag );
ft.attach(mFragment);
ft.show(mFragment); //ib1.6 show fragment ...
ft.commit();
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
debugLog("ExtraContent onTabUnSelected");
ft = mActivity.getSupportFragmentManager()
.beginTransaction();
if (mFragment != null) {
debugLog("hide and detach fragment "+mFragment );
ft.hide(mFragment); //ib1.6 hide fragment ...
ft.detach(mFragment);
ft.commitAllowingStateLoss();
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
debugLog("ExtraContent onTabReSelected");
}
}
void debugLog(String message) {
if (mDebugLog)
Log.d(mDebugTag, message);
}
}

Fragments disappears after resuming

I have a main activity which has actionbarsherlok tabs.Three fragments are placed inside these tabs.After pressing home button and I resume the application immediately from background all fragments are shown without any problem.But, when I try to resume after some time, fragments gets disappeared. I can only see the tab header.For clarification, I am providing the code for main activity,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Drawable d=getResources().getDrawable(R.drawable.tab_bg);
// bar.setBackgroundDrawable(d);
ActionBar.Tab tab1 = bar.newTab();
ActionBar.Tab tab2 = bar.newTab();
ActionBar.Tab tab3 = bar.newTab();
tab1.setText("Holidays");
// tab1.setIcon(R.drawable.abs__ic_menu_share_holo_dark);
tab2.setText("Traveller's Tales");
// tab2.setIcon(R.drawable.abs__ic_voice_search);
tab3.setText("Moments");
// tab3.setIcon(R.drawable.abs__ic_cab_done_holo_dark);
tab1.setTabListener(new MyTabListener());
tab2.setTabListener(new MyTabListener());
tab3.setTabListener(new MyTabListener());
bar.addTab(tab1);
bar.addTab(tab2);
bar.addTab(tab3);
if (Utils.isNetworkAvailable(MainActivity.this)) {
new GetMainCategory(MainActivity.this).execute();
}
else {
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
.create();
alertDialog.setMessage("No network connection!");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Add your code for the button here.
finish();
}
});
alertDialog.show();
}
}
private class MyTabListener implements ActionBar.TabListener {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch (tab.getPosition()) {
case 0:
if (frag1 == null) {
// If not, instantiate and add it to the activity
frag1 = Fragment.instantiate(getApplicationContext(),
PackagesFragment.class.getName());
ft.add(android.R.id.content, frag1, "Feeds");
} else {
// If it exists, simply attach it in order to show it
ft.show(frag1);
}
return;
case 1:
if (frag2 == null) {
// If not, instantiate and add it to the activity
frag2 = Fragment.instantiate(getApplicationContext(),
BlogsFragment.class.getName());
ft.add(android.R.id.content, frag2, "Profile");
} else {
// If it exists, simply attach it in order to show it
ft.show(frag2);
}
return;
case 2:
if (frag3 == null) {
// If not, instantiate and add it to the activity
frag3 = Fragment.instantiate(getApplicationContext(),
GalleryFragment.class.getName());
ft.add(android.R.id.content, frag3, "Gallery");
} else {
// If it exists, simply attach it in order to show it
ft.show(frag3);
}
return;
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
// Detach the fragment, because another one is being attached
switch (tab.getPosition()) {
case 0:
ft.hide(frag1);
return;
case 1:
ft.hide(frag2);
return;
case 2:
ft.hide(frag3);
return;
}
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
//Here I have an async task.
}
ft.show(frag1);
should be
ft.attach(frag1); etc. if you're following this.

Run code in ActionBar Tab Fragment when tab is removed

I've got Fragment ActionBar Tabs with an TabListener attached to every tab. In my main activity I got a delete tab button as follows:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()
case R.id.closeTab:
closeTab();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void closeTab() {
if(getActionBar().getTabCount() > 1) {
Tab tab = getActionBar().getSelectedTab();
getActionBar().removeTab(tab);
}
}
What I'm trying to accomplish is to run some code in my tab-fragment before it gets removed. I could place this in the fragments onDestroyView() or onDestroy() but I only whant to run this code when I press my delete tab button.
I have checked the documentation for the TabListener but it seems like TabListener only listens to selectionchanges.
My TabListener:
public TabListener(Activity a, String t, Class<T> c) {
activity = a;
tag = t;
myClass = c;
}
/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (fragment == null) {
// If not, instantiate and add it to the activity
fragment = Fragment.instantiate(activity, myClass.getName());
ft.add(android.R.id.content, fragment, tag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(fragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (fragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(fragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
To clarify my question: How can I run code in my Fragment before the tab is removed?
Okey, I figured it out after reading this post: link.
In my fragment I put setHasOptionMenu(true)
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
And then I could just add onOptionsItemSelected in my fragment.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.closeTab:
closeTab();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void closeTab() {
ActionBar actionBar = getActivity().getActionBar();
if(actionBar.getTabCount() > 1) {
Tab tab = actionBar.getSelectedTab();
actionBar.removeTab(tab);
Log.d(TAG, "CLOSED TAB");
}
}

Categories

Resources