I am adding fragment like bellow :
#OnClick(R.id.lnNews)
void newsList() {
String tagName = returnStatusFragment(getString(R.string.news_list_fragment));
if (!TextUtils.isEmpty(tagName) && tagName.equals(getString(R.string.news_list_fragment))) {
frameWorkTableFragment.setVisibility(View.VISIBLE);
if (getActivity() != null) {
android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
Fragment news = fragmentManager.findFragmentByTag(getString(R.string.news_list_fragment));
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_work_table_fragment,
news,
getString(R.string.news_list_fragment)).commit();
}
//Fragment is opened
} else {
if (getActivity() != null) {
frameWorkTableFragment.setVisibility(View.VISIBLE);
NewsListFragment newsListFragment = new NewsListFragment();
getActivity().getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_work_table_fragment,
newsListFragment,
getString(R.string.news_list_fragment))
.addToBackStack(getString(R.string.news_list_fragment))
.commit();
}
}
}
And in the Fragment I wrote doBackPress like bellow :
#Override
public void doBackTabZero(String nameFragment) {
android.support.v4.app.FragmentManager fragmentManagers = getActivity().getSupportFragmentManager();
if (fragmentManagers.getBackStackEntryCount() > 1) {
fragmentManagers.popBackStackImmediate();
} else {
if (nameFragment.equals("SignsFragment")) {
BusDisplayStatusFrameLayout busDisplayStatusFrameLayout = new BusDisplayStatusFrameLayout();
busDisplayStatusFrameLayout.setDisplayStatusFrameLayout(1);
EventBus.getDefault().post(busDisplayStatusFrameLayout);
android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentManager.popBackStackImmediate();
fragmentTransaction.remove(SignsFragment.this);
fragmentTransaction.commit();
}
}
}
But get me crash often in this line :
fragmentManagers.popBackStackImmediate();
With this message :
java.lang.IllegalStateException: Fragment already added: NewsFragment{aed4cd1 #3 id=0x7f0a006e NewsFragment}
And in my activity my doBack is like bellow :
private Fragment getCurrentFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
String fragmentTag = fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName();
return fragmentManager.findFragmentByTag(fragmentTag);
}
Then :
#Override
public void onBackPressed() {
int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
if (backStackEntryCount > 0) {
if (onBackPressedListenerTabWorkTable != null || onBackPressedListenerTabMou != null) {
if (getCurrentFragment().getTag() != null && !TextUtils.isEmpty(getCurrentFragment().getTag())) {
if (getCurrentFragment().getTag().equals("EventsFragment")
|| getCurrentFragment().getTag().equals("WebViewListClassFragment")
|| getCurrentFragment().getTag().equals("SignsFragment")
|| getCurrentFragment().getTag().equals("NewsListFragment")) {
if (viewPagerMainActivity.getCurrentItem() != 0) {
viewPagerMainActivity.setCurrentItem(0);
}
onBackPressedListenerTabWorkTable.doBackTabZero(getCurrentFragment().getTag());
} else if (getCurrentFragment().getTag().equals("SpecialNewsMouFragment")) {
if (viewPagerMainActivity.getCurrentItem() != 1) {
viewPagerMainActivity.setCurrentItem(1);
}
onBackPressedListenerTabMou.doBackTabOne(getCurrentFragment().getTag());
}
}
}
} else {
super.onBackPressed();
onBackPressedListenerTabWorkTable = null;
onBackPressedListenerTabMou = null;
finish();
}
}
I have a viewpager. The viewpager has five fragments. And these fragments have child fragments. When I start my app, it crashes. If I comment out resetMenu() function it works. What is the problem?
HomeActivity.java
#Override
public void onPageSelected(int position) {
listeners[beforePagerPosition].onViewPaused();
tabLayout.getTabAt(beforePagerPosition).getIcon().setAlpha(getResources().getInteger(R.integer.tab_unselected_alpha));
beforePagerPosition = position;
tabLayout.getTabAt(position).getIcon().setAlpha(getResources().getInteger(R.integer.tab_selected_alpha));
listeners[position].onViewResumed();
resetMenu();
hideKeyboard();
}
#Override
public void onPageScrollStateChanged(int state) {
}
private void resetMenu() {
if (getSupportFragmentManager() != null) {
ParentFragment parentFragment = (ParentFragment) listeners[viewPager.getCurrentItem()];
FragmentManager fm = parentFragment.getChildFragmentManager();
if (fm != null && fm.getBackStackEntryCount() > 0) {
FragmentManager.BackStackEntry backStackEntry = fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1);
String str = backStackEntry.getName();
BaseMenuFragment fragment = (BaseMenuFragment) fm.findFragmentByTag(str);
fragment.setHasOptionsMenu(true);
}
}
}
OK. I found answer. I added control for ParentFragment isAdded().
ParentFragment parentFragment = (ParentFragment) listeners[viewPager.getCurrentItem()];
if(parentFragment.isAdded()){
....
}
I have to include three Fragment on my main Activity on click of Three Buttons on app bar. Now, Question is I want to go back from second activity to specific fragment on mainActivity I am using Intent but at start of app intent is null and get nullpointer exception and app crash.
Here is MainActivity.java
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
FragmentTransaction fragmentTransaction;
HomeFragment homeFrag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
//--------Set and Get Tool Bar-------//
setSupportActionBar(binding.appbar);
getSupportActionBar().setTitle("");
if(getIntent() !=null){
String is = getIntent().getStringExtra("check");
if(is.equals("1")){
SearchFragment searchFrag = new SearchFragment();
if(searchFrag != null){
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, searchFrag)
.addToBackStack(null).commit();
}
}
}else{
homeFrag = new HomeFragment();
if(homeFrag!=null) {
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, homeFrag).commit();
}
}
}
public void MoveToSearchActivity(View view){
SearchFragment searchFag = new SearchFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer,searchFag).commit();
}
public void MoveToHomeActivity(View view){
if(homeFrag!=null) {
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer, homeFrag).commit();
}
}
public void MoveToAlertFrag(View view){
AlertFragment alertFragment = new AlertFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragmentContainer,alertFragment).commit();
}
And here is my FilterActivity.java from which I'm going back to fragment:
public class FilterActivity extends AppCompatActivity{
private ActivityFilterBinding binding;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filter);
//--------------Get ToolBar-----------//
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(" ");
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Intent homeIntent = new Intent(FilterActivity.this, MainActivity.class);
homeIntent.putExtra("check",1);
startActivity(homeIntent);
break;
default:
break;
}
return true;
}
}
Thanks.
Try this in MainActivity,
// Toolbar code
...
int is = -1;
if (getIntent() != null && getIntent().hasExtra("check")) {
is = getIntent().getIntExtra("check", -1);
}
switch (is) {
case 1:
// load SearchFragment
break;
case 2:
// load MoveToAlertFrag
break;
default:
// load HomeFragment
break;
}
I receive IllegalStateException : Fragment already added when changing screen orientation. I have one Activity and three fragments
CODE:
private Fragment mFragment;
...
#Override
protected void onCreate(Bundle savedInstanceState) {
initViews();
setBackStackBehavior();
mFragment = getSupportFragmentManager().findFragmentByTag(Constants.FIND_FRAGMENT_BY_TAG);
if (mFragment == null) {
mFragment = new SectionFragment();
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, mFragment, Constants.FIND_FRAGMENT_BY_TAG).commit();
private void setBackStackBehavior() {
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSupportFragmentManager().popBackStack();
getSupportFragmentManager().executePendingTransactions();
}
});
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
mDrawerToggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
});
}
Also I can move to the First Fragment :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.section_selection:
mFragment = new SectionFragment();
getSupportFragmentManager().beginTransaction()
.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left,
R.anim.enter_from_left, R.anim.exit_to_right)
.replace(R.id.container, mFragment, Constants.FIND_FRAGMENT_BY_TAG)
.commit();
return true;
case R.id.exit:
finish();
default:
return super.onOptionsItemSelected(item);
}
}
I tried to create ArrayList<Fragment> mAdded and add here Fragment after transaction and then,when all fragments was added :
if(mAdded.contains(mFragment.getClass())){
getSupportFragmentManager().beginTransaction()
.show( mFragment).commit();
}
It did not help. Tried to remove Fragment in onPause(), but it did not solve my problem too. I tried to use commitAllowingStateLoss () instead commit()
How to fix this bug?
In oncreate check whether saved instance state is null if not don't replace the fragment.Also you can check whether your fragment is already added and available by using find fragment by id.
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container,
mFragment,Constants.FIND_FRAGMENT_BY_TAG).commit();
}
or
if(((Fragment) getSupportFragmentManager().findFragmentByTag(Constants.FIND_FRAGMENT_BY_TAG)) == null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.container,
mFragment,Constants.FIND_FRAGMENT_BY_TAG).commit();
}
I've been searching and thinking how to implement the desire behaviour that I want when switching back and forth between fragments when using a Navigation Drawer. Actually the documentation says:
When using fragments in your app, individual FragmentTransaction objects may represent context changes that should be added to the back stack. For example, if you are implementing a master/detail flow on a handset by swapping out fragments, you should ensure that pressing the Back button on a detail screen returns the user to the master screen
So in my app I have a MainActivity that controls everything and a navigation layout within you can change between predefined options. This is the view when you launch the app
When you click on an item in the navigation drawer it opens a new fragment that replaces the main_content as follows:
At this point the behaviour is the correct one, so if you want to change the options you need to open the navigation drawer again to toggle between the menu options.
This is the Main Activity (notice that there is no Drawer Toggle)
MainActivity.java
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout drawerLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSnackBarView = findViewById(R.id.myCoordinatorLayout);
setToolbar(); // Set Toolbar como action bar
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
drawerTitle = getResources().getString(R.string.app_name);
if (savedInstanceState == null) {
selectItem(drawerTitle, mCurrentSelectedPosition);
}
}
private void setToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
if (ab != null) {
// Poner ícono del drawer toggle
ab.setHomeAsUpIndicator(R.drawable.ic_menu);
ab.setDisplayHomeAsUpEnabled(true);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Marcar item presionado
menuItem.setChecked(true);
// Crear nuevo fragmento
String title = menuItem.getTitle().toString();
int id = menuItem.getItemId();
selectItem(title, id);
return true;
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectItem(String title, int id) {
Bundle args = new Bundle();
args.putString(PlaceholderFragment.ARG_SECTION_TITLE, title);
Fragment fragment = PlaceholderFragment.newInstance(title);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
switch (id) {
case R.id.nav_localizacion:
//Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 0;
LocalizacionFragment fragment_localizacion = new LocalizacionFragment();
// fragmentManager = getSupportFragmentManager();
Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_localizacion)
.commit();
break;
case R.id.nav_productos:
Snackbar.make(mSnackBarView, R.string.menu_productos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 1;
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
break;
case R.id.nav_consejos:
Snackbar.make(mSnackBarView, R.string.menu_consejos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 3;
ConsejosFragment fragment_consejo = new ConsejosFragment();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_consejo)
.commit();
break;
default:
break;
}
drawerLayout.closeDrawers(); // Cerrar drawer
setTitle(title); // título actual
}
}
I don't use the hamburger icon because it hides under the Navigation Layout, but here is the thing. When you click on "Recetas" in the recycle view it open a new fragment (replace) but now I want to show the up caret icon and give proper back navigation to my app.
Here is the code of the "Consejos" fragment class
Consejos.java
public class ConsejosFragment extends Fragment {
RecyclerView mRecycler;
ConsejosAdapter mAdapter;
FragmentActivity mActivity;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.mActivity = (FragmentActivity) activity;
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
List items = new ArrayList();
items.add(new ConsejosInfo("Recetas", R.drawable.icon_recetas));
/* Inflamos el layout */
View v = inflater.inflate(R.layout.consejos_layout_recycler, container, false);
/* Obtenemos el Recycle */
mRecycler = (RecyclerView) v.findViewById(R.id.recycler_consejos);
/* Creamos el adaptador */
mAdapter = new ConsejosAdapter(mActivity, items);
/* Set click en adapter */
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRecycler.setHasFixedSize(true);
mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecycler.setAdapter(mAdapter);
}
}
And this is the adapter that the Recyclerview use and handles the click on the item inside:
Adapter.java
public class ConsejosAdapter extends RecyclerView.Adapter<ConsejosAdapter.ConsejosViewHolder> {
private List<ConsejosInfo> _items = new ArrayList<ConsejosInfo>();
private final FragmentActivity mActivity;
private Context context;
public ConsejosAdapter(FragmentActivity mActivity, List<ConsejosInfo> items) {
this._items = items;
this.mActivity = mActivity;
}
#Override
public int getItemCount() {
return _items.size();
}
#Override
public ConsejosViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardview_consejos, viewGroup, false);
return new ConsejosViewHolder(v);
}
#Override
public void onBindViewHolder(ConsejosViewHolder viewHolder, int position) {
viewHolder.imagen.setImageResource(_items.get(position).get_imagen());
viewHolder.nombre.setText(_items.get(position).get_nombre());
}
public class ConsejosViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView imagen;
public TextView nombre;
public ConsejosViewHolder(final View itemView) {
super(itemView);
imagen = (ImageView) itemView.findViewById(R.id.consejos_imagen);
nombre = (TextView) itemView.findViewById(R.id.consejos_nombre);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
RecetasFragment recetasFragment = new RecetasFragment();
FragmentManager fragmentManager = mActivity.getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, recetasFragment)
.addToBackStack(null)
.commit();
}
}
}
In the Consejos Adapter I added to backstack the fragment before calling the new fragment (inside fragment) and that changes the behaviour of the back button, so before this if you press the back button is closes the app but now it takes you to the Consejos fragment, but now I want to add the up caret and make the exactly same operation as when you click the back button but I don't know how to achieve it.
Please feel free to ask for more code
Thank you very much
I will give you the full answer:
We will use the interfaces to communicate with the MainActivity from RecetasFragment so we can enable and disable navigation back button.
RecetasFragment class:
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by hema on 8/19/2015.
*/
public class RecetasFragment extends Fragment {
private CommunicateWithActivity mWithActivity;
public RecetasFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mWithActivity = (CommunicateWithActivity) activity; // MainActivity must implement CommunicateWithActivity interface.
mWithActivity.enableNavigationBack(true); // We enable navigation back here.
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement CommunicateWithActivity");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_recetas, container, false);
}
#Override
public void onDestroy() {
super.onDestroy();
mWithActivity.enableNavigationBack(false); // We disable navigation back here, restore menu icon.
}
public interface CommunicateWithActivity {
void enableNavigationBack(boolean enable);// we will implement this method in MainActivity class.
}
}
And in MainActivity class we will implement CommunicateWithActivity interface, Modify your MainActivity class (only required modifications):
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity implements RecetasFragment.CommunicateWithActivity {
private Toolbar mToolbar;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mToolbar.setNavigationIcon(R.drawable.ic_menu);
mSnackBarView = findViewById(R.id.myCoordinatorLayout);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
drawerTitle = getResources().getString(R.string.app_name);
if (savedInstanceState == null) {
selectItem(drawerTitle, mCurrentSelectedPosition);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Marcar item presionado
menuItem.setChecked(true);
// Crear nuevo fragmento
String title = menuItem.getTitle().toString();
int id = menuItem.getItemId();
selectItem(title, id);
return true;
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!drawerLayout.isDrawerOpen(GravityCompat.START)) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void selectItem(String title, int id) {
Bundle args = new Bundle();
args.putString(PlaceholderFragment.ARG_SECTION_TITLE, title);
Fragment fragment = PlaceholderFragment.newInstance(title);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
switch (id) {
case R.id.nav_localizacion:
//Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 0;
LocalizacionFragment fragment_localizacion = new LocalizacionFragment();
// fragmentManager = getSupportFragmentManager();
Snackbar.make(mSnackBarView, R.string.menu_localization, Snackbar.LENGTH_SHORT).show();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_localizacion)
.commit();
break;
case R.id.nav_productos:
Snackbar.make(mSnackBarView, R.string.menu_productos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 1;
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment)
.commit();
break;
case R.id.nav_consejos:
Snackbar.make(mSnackBarView, R.string.menu_consejos, Snackbar.LENGTH_SHORT).show();
mCurrentSelectedPosition = 3;
ConsejosFragment fragment_consejo = new ConsejosFragment();
fragmentManager
.beginTransaction()
.replace(R.id.main_content, fragment_consejo)
.commit();
break;
default:
break;
}
drawerLayout.closeDrawers(); // Cerrar drawer
setTitle(title); // título actual
}
#Override
public void enableNavigationBack(boolean enable) {
if(enable) {
// We enable the navigation back button here
mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// On navigation back button clicked.
if(getSupportFragmentManager().getBackStackEntryCount() > 0) { // Check if there is fragments in BackStack.
getSupportFragmentManager().popBackStack(); // PopBackStack.
} else {
// You can implement this part as you want.
return;
}
}
});
} else {
mToolbar.setNavigationIcon(R.drawable.ic_menu);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(drawerLayout != null) {
drawerLayout.openDrawer(Gravity.LEFT);
}
}
});
}
}
}
Please let me know if there is something you don't understand.