I'm having a difficulty to show a fragment in a container when a menu item is clicked.Below is my code.
I tried to do ft.show(); inside onMenuItemClick of Login Menu Item but its not working and I don't know what am I doing wrong as I'm neither getting any errors nor the app is crashing. Fragments which are attached to the Tabs are working and displaying just fine. It's just that when I try to load a fragment in an container when menu item is clicked at that time nothing happens.Please point me in a right direction and lemme know what am I doing wrong.
public class HomeActivity extends SherlockFragmentActivity {
public SherlockFragment fragment;
FragmentTransaction ft;
public static Context appContext;
ActionBar actionbar;
String mCurFilter;
LoginScreenFragment loginFragment;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
appContext = getApplicationContext();
actionbar = getSupportActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab HomeTab = actionbar.newTab().setText("Home");
ActionBar.Tab CartTab = actionbar.newTab().setText("Cart");
ActionBar.Tab myTab = actionbar.newTab().setText("MyFragment");
ActionBar.Tab moreTab = actionbar.newTab().setText("More...");
HomeFragment homeFragment = new HomeFragment();
CartFragment cartFragment = new CartFragment();
MyFragment myFragment = new MyFragment();
MoreFragment moreFragment = new MoreFragment();
loginFragment = new LoginScreenFragment();
HomeTab.setTabListener(new MyTabsListener(homeFragment));
CartTab.setTabListener(new MyTabsListener(cartFragment));
myTab.setTabListener(new MyTabsListener(myFragment));
moreTab.setTabListener(new MyTabsListener(moreFragment));
actionbar.addTab(HomeTab);
actionbar.addTab(CartTab);
actionbar.addTab(myTab);
actionbar.addTab(moreTab);
ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragment_container, homeFragment);
ft.show(homeFragment);
ft.add(R.id.fragment_container, cartFragment);
ft.hide(cartFragment);
ft.add(R.id.fragment_container, myFragment);
ft.hide(myFragment);
ft.add(R.id.fragment_container, moreFragment);
ft.hide(moreFragment);
ft.add(R.id.fragment_container, loginFragment);
ft.hide(loginFragment);
ft.commit();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getSupportActionBar()
.getSelectedNavigationIndex());
System.out.println("onSaveInstanceState");
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
MenuItem item = menu.add("Search");
item.setIcon(android.R.drawable.ic_menu_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
View searchView = SearchViewCompat.newSearchView(this);
if (searchView != null) {
SearchViewCompat.setOnQueryTextListener(searchView,
new OnQueryTextListenerCompat() {
#Override
public boolean onQueryTextChange(String newText) {
mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;
return true;
}
});
item.setActionView(searchView);
}
MenuItem loginItem = menu.add("Login");
loginItem.setTitle("Login");
loginItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
loginItem.setOnMenuItemClickListener(new OnMenuItemClickListener(){
#Override
public boolean onMenuItemClick(MenuItem item) {
//I wanted to show "loginFragment" when the Login button is clicked.But unfortunately its not showing up.Also the application is not giving any errors or crashing
ft.show(loginFragment);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menuitem_home) {
Toast.makeText(appContext, "Home", Toast.LENGTH_SHORT).show();
return true;
} else if (itemId == R.id.menuitem_shop) {
Toast.makeText(appContext, "Shop", Toast.LENGTH_SHORT).show();
return true;
} else if (itemId == R.id.menuitem_cart) {
Toast.makeText(appContext, "Cart", Toast.LENGTH_SHORT).show();
return true;
} else if (itemId == R.id.menuitem_my) {
Toast.makeText(appContext, "My", Toast.LENGTH_SHORT).show();
return true;
} else if (itemId == R.id.menuitem_more) {
Toast.makeText(appContext, "More...", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
static class MyTabsListener implements ActionBar.TabListener {
public SherlockFragment fragment;
public MyTabsListener(SherlockFragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
System.out.println("TabReselected " + tab.getPosition());
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
System.out.println("TabSelected " + tab.getPosition());
ft.show(this.fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
System.out.println("TabUnselected " + tab.getPosition());
ft.hide(this.fragment);
}
}
}
Instead of adding the fragments to one container and hiding & showing them you can try replacing fragments when you click on your menu buttons.
for ex- when you click on login button
ft.replace(R.id.fragment_container, loginFragment).commit();
give it a try hope it will work.
You should begin and commit the transaction again. Try:
#Override
public boolean onMenuItemClick(MenuItem item) {
ft = getSupportFragmentManager().beginTransaction();
ft.show(loginFragment);
ft.commit();
return false;
}
Related
I have a Mainactivity which contains a Layout which is parent of 4 sub layout. on clicking on sub layout i am going to a new fragment replacing main layout. But i cant go back to MainActivity after pressing Back button
MainActivity.java
public class MainActivity extends AppCompatActivity {
RelativeLayout aboutUs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
aboutUs = (RelativeLayout) findViewById(R.id.aboutUs);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
//click methods goes here
public void clickAboutUs(View view){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentAboutUs fragmentAboutUs = new FragmentAboutUs();
fragmentTransaction.replace(R.id.fragment_container,fragmentAboutUs);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
FragmentAboutUs.java
public class FragmentAboutUs extends Fragment
{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.about_us, container,false);
return view;
}
}
How to go back to main page again after pressing back button from fragment.
Try Like this
public boolean popFragment() {
boolean isPop = false;
Fragment currentFragment = getSupportFragmentManager()
.findFragmentById(R.id.flContent);
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
isPop = true;
getSupportFragmentManager().popBackStackImmediate();
}
return isPop;
}
#Override
public void onBackPressed() {
if (!popFragment()) {
finish();
}
}
public void replaceFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
if (addToBackStack) {
transaction.addToBackStack(null);
} else {
getSupportFragmentManager().popBackStack(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
getSupportFragmentManager().executePendingTransactions();
}
add above method is in your parent Activity
And Use like
FragmentAboutUs fragmentAboutUs = new FragmentAboutUs();
replaceFragment(fragmentAboutUs , true);
If you have one Activity and four fragments then set onBackPressed() as below in your MainActivity.
#Override
public void onBackPressed()
{
super.onBackPressed();
finish();
}
And in fragments:
#Override
public void onResume() {
super.onResume();
new PlayListFragment();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
return true;
}
return false;
}
});
}
You can Override the onBackPressed of MainActivity
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Here is how it can be done in Xamarin:
Load fragment (I wrote helper method for that, but it's not necessary):
public void LoadFragment(Activity activity, Fragment fragment)
{
var backStateName = fragment.GetType().Name;
var fm = activity.FragmentManager;
var ft = fm.BeginTransaction();
ft.Replace(Resource.Id.mainContainer, fragment);
ft.AddToBackStack(backStateName);
ft.Commit();
}
Back button (in MainActivity):
public override void OnBackPressed()
{
if (isNavDrawerOpen()) drawerLayout.CloseDrawers();
else
{
var backStackEntryCount = FragmentManager.BackStackEntryCount;
if (backStackEntryCount == 1) Finish();
else if (backStackEntryCount > 1) FragmentManager.PopBackStack();
else base.OnBackPressed();
}
}
isNavDrawerOpen method:
bool isNavDrawerOpen()
{
return drawerLayout != null && drawerLayout.IsDrawerOpen(Android.Support.V4.View.GravityCompat.Start);
}
I am trying to refresh the fragment depending on what drawer the user is on...
This was my attempt which does not do anything but does not give me an error.
Here is my code
public void fragmentRefresh() {
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragmentManager.findFragmentByTag("TagForRefresh"))
.commit();
}
Here is the drawer fragment code:
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new BrowseFragment();
break;
case 2:
fragment = new InviteFragment();
break;
case 3:
fragment = new ProfileFragment();
break;
case 4:
fragment = new SettingsFragment();
break;
case 5:
callConfirmLogout();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment, "TagForRefresh").commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
Implemented in a tab swiper fragment class:
public class ViewVotesActivity extends FragmentActivity implements ActionBar.TabListener{
//Tab options
private ViewPager viewPager;
private TabSwipeAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Created", "Up", "Down"};
//for custom menu to add progress bar to refresh
private MenuItem menuItem;
//Search view action bar
private SearchView search_action_bar;
//getApplicationContext().getString(R.string.created),getApplicationContext().getString(R.string.upvote), getApplicationContext().getString(R.string.downvote)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_votes);
// Initializing tab
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabSwipeAdapter(getSupportFragmentManager(), new UserCreatedFragment(), new UserUpVotesFragment(),new UserDownVotesFragment());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
setupActions(menu);
callSearchActionBar(menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_refresh:
menuItem = item;
menuItem.setActionView(R.layout.refresh_progress_bar);
//menuItem.expandActionView();
fragmentRefresh();
TestTask task = new TestTask();
task.execute("test");
return true;
case R.id.action_discover:
addNewItem();
return true;
case R.id.action_search:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void addNewItem() {
// user redirect to register followup
Intent createItemIntent = new Intent(ViewVotesActivity.this, CreateItemActivity.class);
// Closing all the Activities
createItemIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
createItemIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(createItemIntent);
}
public void fragmentRefresh() {
// // Insert the fragment by replacing any existing fragment
// FragmentManager fragmentManager = getFragmentManager();
//
// fragmentManager.beginTransaction()
// .replace(R.id.frame_container, fragmentManager.findFragmentByTag("TagForRefresh"))
// .commit();
}
private class TestTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Simulate something long running
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
menuItem.collapseActionView();
menuItem.setActionView(null);
}
};
public void setupActions(Menu menu) {
MenuItem refreshItem = menu.findItem(R.id.action_refresh);
MenuItem discoverItem = menu.findItem(R.id.action_discover);
if (isAlwaysExpanded()) {
} else {
refreshItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
discoverItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
}
public void callSearchActionBar(Menu menu) {
//find the menu item and set search view at the same time
MenuItem searchItem = menu.findItem(R.id.action_search);
search_action_bar
= (SearchView) searchItem.getActionView();
if (isAlwaysExpanded()) {
search_action_bar.setIconifiedByDefault(false);
} else {
searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM
| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
}
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if (searchManager != null) {
List<SearchableInfo> searchables = searchManager.getSearchablesInGlobalSearch();
SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
for (SearchableInfo inf : searchables) {
if (inf.getSuggestAuthority() != null
&& inf.getSuggestAuthority().startsWith("applications")) {
info = inf;
}
}
search_action_bar.setSearchableInfo(info);
}
search_action_bar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
Log.e("Query = ", newText);
return false;
}
public boolean onQueryTextSubmit(String query) {
Log.e("Submit", "Submited " + query);
// user redirect to register followup
Intent searchIntent = new Intent(ViewVotesActivity.this, SearchActivity.class);
searchIntent.putExtra("search", query);
// Closing all the Activities
searchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
searchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
startActivity(searchIntent);
return false;
}
public boolean onClose() {
Log.e("query close", "query closingggg");
return false;
}
});
}
protected boolean isAlwaysExpanded() {
return false;
}
}
UPDATE:
It looks like you're trying to tell an Activity that it's time to change the content fragment depending upon a selection in a Navigation Drawer.
This problem has two parts.
You need to provide a mechanism to communicate from your Drawer to your Activity, which, will, in turn, proceed to perform the necessary actions.
Your Fragments must either be Detached, Destroyed, Recreated and Reattached (inneficient, why?) or simply implement a mechanism that tells them: Hey, it's time to Refresh your content.
I don't see any reason why you need to completely destroy the Fragment's view if you only need to reset its data. Seems like a design flaw.
Replacing a Fragment should not mean you want to completely destroy it, since the user can simply go back or press the recently removed fragment. It would be inefficient to recreate it again.
Like I mentioned in the comments, more code is needed to see what your current approach is.
Normally a simple Interface (like the one I described below) should suffice. Your activity can receive the "clicks" in the Drawer and decide which fragment to replace (if needed).
Please be a lot more specific and provide more code.
Old Response:
Warning: if you're trying to replace the current fragment, make sure you're not getting the wrong FragmentManager. You do getFragmentManager() but I'm sure you're using the support library and therefore need to do getSupportFragmentManager();.
You've failed to mention what version you're targeting so it's hard to know.
On the other hand,
If what you want to do is tell the current visible fragment to refresh… you should use a more common approach to object-to-object communication.
You're over-complicating things.
(warning: pseudo code)
Create an interface like:
public interface Refreshable{
void onShouldRefresh();
}
Have a DrawerController capable of storing observers/listeners…
public class DrawerController {
private List<Refreshable> mListeners = new ArrayList<Refreshable>();
public void addRefreshListener(E listener) {
if (listener != null && !mListeners.contains(listener)) {
mListeners.add(listener);
}
}
public void removeRefreshListener(E listener) {
if (listener != null) {
mListeners.remove(listener);
}
}
}
Make your fragments implement it (and subscribe to the event when they are visible)
public class HomeFragment extends Fragment implements Refreshable {
// your fragment code
public void onShouldRefresh(){
// do the refresh
}
#Override
public void onResume() {
super.onResume();
yourDrawerController.addRefreshListener(this);
}
#Override
public void onPause() {
super.onPause();
yourDrawerController.removeRefreshListener(this);
}
}
Now make a method that will tell the interested parties (in this case your "Refreshable" objects) that it's time to refresh, add this to your DrawerController…
public void refresh(){
for (Refreshable listener : mListeners) {
if (listener != null) {
listener.onShouldRefresh();
}
}
}
Finally, in your code, call refresh() and have a beer.
Did I miss your point? it's not 100% clear to me.
here my problem ill explain.Initially first tab ill be selected and next if i click second tab, its work well but again click first tab my app ill be closed. could you suggest me for this.
here my code.
public class MainActivity extends Activity {
public static Context appContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab connectionTab = actionbar.newTab().setText("Connection");
ActionBar.Tab masterDataTab = actionbar.newTab().setText("Master Data");
Fragment connection = new AFragment();
Fragment masterData = new BFragment();
connectionTab.setTabListener(new MyTabsListener(connection));
masterDataTab.setTabListener(new MyTabsListener(masterData));
actionbar.addTab(connectionTab);
actionbar.addTab(masterDataTab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
}
return false;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
//ft.replace(R.id.fragment_container, 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);
}
}
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");
}
}
I have created action bar.in that when i click on one of the menu a pop window should be displayed.I have done that.But after the pop up window displays i am not able to perform other function in my action bar.howw can i acheive that.I have posted my code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mDisplayMode = tab.getPosition();
System.out.println("text");
// Do stuff based on new tab selected
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// Do Nothing
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// Do nothing
}*/
ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tabA = bar.newTab().setText("Home");
ActionBar.Tab tabB = bar.newTab().setText("Listings");
ActionBar.Tab tabC = bar.newTab().setText("Remote");
Fragment fragmentA = new ATab();
Fragment fragmentB = new BTab();
Fragment fragmentC = new CTab();
bar.setDisplayShowHomeEnabled(true);
tabA.setTabListener(new MyTabsListener(fragmentA));
tabB.setTabListener(new MyTabsListener(fragmentB));
tabC.setTabListener(new MyTabsListener(fragmentC));
bar.addTab(tabA);
bar.addTab(tabB);
bar.addTab(tabC);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.settings:
newGame();
return true;
case R.id.help:
// showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void newGame() {
LayoutInflater inflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
PopupWindow pw = new PopupWindow(
inflater.inflate(R.layout.settings, null, true), 300, 600, true);
// The code below assumes that the root container has an id called 'main'
pw.showAtLocation(this.findViewById(R.id.settings), Gravity.RIGHT, 0, 0);
}
protected class MyTabsListener implements ActionBar.TabListener {
private Fragment mfragment;
public MyTabsListener(Fragment fragment) {
this.mfragment = fragment;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.add(R.id.fragment_place, mfragment, null);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.remove(mfragment);
}
}
}