I have already add an bottom navigation bar into my project with 3 fragments (Home_fragment, Wallet_fragment, Account_fragment). I have added login button in Account_fragment. Now I want that Whenever I click on login button login_fragment (afterlogin activity) open with bottom navigation bar.
I have attaching a link to video showing my problem:
https://cloud.degoo.com/share/o41Axz4FYFHBx7
And here is code, starting with mainActivity:
BottomNavigationView bottomNavigationView = findViewById(R.id.main_nav);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.main_frame_layout, new HomeFragment()).commit();
}
BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selecrFlag = null;
switch (menuItem.getItemId())
{
case R.id.nav_home:
selecrFlag = new HomeFragment();
break;
case R.id.nav_wallet:
selecrFlag = new WalletFragment();
break;
case R.id.nav_Account:
selecrFlag = new AccountFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.main_frame_layout, selecrFlag).commit();
return true;
}
};
};
Account_fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_account, container, false);
EmailID = v.findViewById(R.id.editTextEmail);
Passwd = v.findViewById(R.id.editPassword);
SignUpBt = v.findViewById(R.id.signbutton);
LoginBt = v.findViewById(R.id.loginbutton);
LoginBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(AccountFragment.this.getContext(),AfterLogin.class));
}
});
afterlogin Fragment:
package com.thechamp.earnbyads;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class AfterLogin extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
}
}
Related
this is the web view fragment
public class Home extends Fragment {
public Home() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_home, container, false);
WebView webView = (WebView)v.findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://www.google.com");
return v;
}
}
I created web view inside other fragment not in main activity and when I press back button the app will close. so how to go back only inside web view (not through fragments)? please give me a solution.
here is my main activity
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "MainActivity";
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottom_navigation_view);
bottomNavigationView.setOnNavigationItemSelectedListener(this);
bottomNavigationView.setSelectedItemId(R.id.navigation_home);
}
Home homeFragment = new Home();
Live_And_Event_Schedule live_and_event_scheduleFragment = new Live_And_Event_Schedule();
Photos photosFragment = new Photos();
Videos videosFragment = new Videos();
About aboutFragment = new About();
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.navigation_home:
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out).replace(R.id.center, homeFragment).commit();
return true;
case R.id.navigation_live_and_event_schedule:
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out).replace(R.id.center, live_and_event_scheduleFragment).commit();
return true;
case R.id.navigation_photos:
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out).replace(R.id.center, photosFragment).commit();
return true;
case R.id.navigation_videos:
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out).replace(R.id.center, videosFragment).commit();
return true;
case R.id.navigation_about:
getSupportFragmentManager().beginTransaction().setCustomAnimations(R.anim.fade_in, R.anim.fade_out).replace(R.id.center, aboutFragment).commit();
return true;
}
return false;
}
}
you can override onBackPressed in the Activity. save all fragmentTransaction before addToBackStack
#Override
public void onBackPressed() {
int count = getSupportFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
//add extra code
} else {
getSupportFragmentManager().popBackStack();
}
}
I have already add an bottom navigation bar into my project with 3 fragments (Home_fragment, Wallet_fragment,Account_fragment). I have added login button in Account_fragment. Now i want that When ever i click on login button login_fragment(afterlogin_fragment) open with bottom navigation bar.
I have attaching a link to video showing my problem. link -- https://cloud.degoo.com/share/o41Axz4FYFHBx7
and here is codes ---
mainActivity ---
BottomNavigationView bottomNavigationView = findViewById(R.id.main_nav);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
getSupportFragmentManager().beginTransaction().replace(R.id.main_frame_layout, new HomeFragment()).commit();
}
BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment selecrFlag = null;
switch (menuItem.getItemId())
{
case R.id.nav_home:
selecrFlag = new HomeFragment();
break;
case R.id.nav_wallet:
selecrFlag = new WalletFragment();
break;
case R.id.nav_Account:
selecrFlag = new AccountFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.main_frame_layout, selecrFlag).commit();
return true;
}
};
};
Account_fragment ---
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_account, container, false);
EmailID = v.findViewById(R.id.editTextEmail);
Passwd = v.findViewById(R.id.editPassword);
SignUpBt = v.findViewById(R.id.signbutton);
LoginBt = v.findViewById(R.id.loginbutton);
LoginBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(AccountFragment.this.getContext(),AfterLogin.class));
}
});
afterlogin Fragment --
package com.thechamp.earnbyads;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class AfterLogin extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_after_login);
}
}
Look like you are confused. the way that you move to another Screen is not Fragment. It is Activity.
There are many ways to deal with this.
you can change your AfterLogin to Fragment.
or implement the AfterLogin Activity as what you implement in your Current Activity that has those 3 Fragments.
I have a problem with android studio. I use a fragment with a bottomNavigationView. It works fine if you click on the bottomNavigation. But if you simulate a click on the bottomNavigation it works for the first time and at the second time if you simulate the performclick again, it does not work.
I used also view.callOnClick(); and for the fragment add and remove fragment, but both do not function for my problem. I really appreciate it, if anyone can solve my problem.
Here is the Code:
`
public class ProfileFragment extends Fragment {
private Button send_order_button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstaceState) {
return inflater.inflate(R.layout.profile_fragment, container,false);
}
#Override
public void onStart() {
send_order_button = (Button) getView().findViewById(R.id.auftrag_abschicken);
}
send_order_button.setOnClickListener(new View.OnClickListener() {
ProfilActivity pa = new ProfilActivity();
pa.changeFragment();
getActivity().finishActivity(ProfilActivity.class.hashCode());
}
}`
`
public class ProfilActivity extends AppCompatActivity {
public ProfilActivity() {}
public static Fragment selectedFragment = null;
public static BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
View view = bottomNavigationView.findViewById(R.id.nav_chat);
view.performClick();
}
public void changeFragment() {
// bottomNavigationView.setSelectedItemId(R.id.nav_store);
View view = bottomNavigationView.findViewById(R.id.nav_store);
view.performClick();
}
public BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_user :
selectedFragment = new ProfileFragment();
break;
case R.id.nav_chat :
selectedFragment = new MailFragment();
break;
case R.id.nav_store:
selectedFragment = new ShopFragment();
break;
}
try {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment, "fragment").commitAllowingStateLoss();
} catch (Exception e) {
e.printStackTrace();
};
return true;
}
};
}`
It looks like you're trying to set the default selected item in the BottomNavigationView. Why not just use bottomNavigationView.setSelectedItemId(R.id.nav_store); ?
This is my main activity where I am calling my fragments:
public class what extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private ListView mDrawerList;
private ArrayAdapter<String> mAdapter;
private FragmentTransaction fragmentTransaction;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_what);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mToggle=new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
fragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_content,new mainfrag());
fragmentTransaction.commit();
ActionBar actionBar= getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
navigationView=(NavigationView)findViewById(R.id.nav_view);
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(0).setChecked(true);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_main:
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setCheckedItem(R.id.nav_main);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new mainfrag());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("SGPA and CGPA Calculator"));
item.setChecked(true);
break;
case R.id.nav_savedcal:
navigationView.getMenu().getItem(0).setChecked(false);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setCheckedItem(R.id.nav_savedcal);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new savedFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("Saved Calculations"));
item.setChecked(true);
break;
case R.id.nav_upldoc:
navigationView.getMenu().getItem(0).setChecked(false);
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setCheckedItem(R.id.nav_upldoc);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new uploadedfragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("Uploaded documents"));
item.setChecked(true);
break;
case R.id.nav_site:
navigationView.getMenu().getItem(0).setChecked(false);
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.setCheckedItem(R.id.nav_site);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new resultsite());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("VTU Results"));
item.setChecked(true);
break;
}
return false;
}
});
}
public boolean onOptionsItemSelected(MenuItem item ){
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE: {
finish();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
return;
}
}
This is my default fragment :
public class mainfrag extends Fragment {
private View view;
private AdView adView;
private Button button10;
private Button button11;
public mainfrag() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_mainfrag, container, false);
adView = view.findViewById(R.id.adView);
button10 = (Button) view.findViewById(R.id.button10);
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openmainactivity();
}
});
button11 = (Button) view.findViewById(R.id.button11);
button11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openscheme();
}
});
return view;
}
public void openmainactivity() {
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
}
public void openscheme(){
Intent intent=new Intent(getContext(), scheme.class);
startActivity(intent);
}
}
This is one of the other fragments:
public class savedFragment extends Fragment {
RecyclerView recyclerview;
adapter_sgpa recyclerAdapter;
ArrayList<POJO> sgpaArrayList;
public savedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentTransaction tx = getChildFragmentManager().beginTransaction();
tx.replace(R.id.container, new sgpa_frag());
tx.commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
switch (id) {
case R.id.navigation_sgpa:
sgpa_frag sf = new sgpa_frag();
FragmentManager fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, sf).commit();
return true;
case R.id.navigation_cgpa:
cgpa_frag cf = new cgpa_frag();
fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, cf).commit();
return true;
}
return false;
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_saved, container, false);
BottomNavigationView nav = (BottomNavigationView) v.findViewById(R.id.bottom_navigation);
nav.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
return v;
}
}
What changes should I make in this code so that I am able to move back from the other fragments to the main fragment on pressing back button ?
Maintain one boolean variable to check current fragment is MainFragment or not.
if its not MainFragment -> replace MainFragment
Else -> super.onBackPressed()
ex:
private boolean isMainFragment=true; //make it false when move to other fragment
#Override
public void onBackPressed() {
if(!isMainFragment){
isMainFragment=true;
//replace your MainFragment
}
else{
//your logic show dialog or super.onBackPressed()
}
}
Ithink I know what you need. have a look at the last part of this documentation
"You can add a fragment transaction to the back stack. The back stack keeps track of actions in your app which can be backtracked when the user clicks Android's standard "back" button on the device. If you add a fragment transaction to the back stack then the transaction can be backtracked (reversed) with a click on the back button on the device" quotet from Jenkov
simply do fragmentTransaction.addToBackStack(null) on your main activity before you do the commit this will allow you to travel back using the back button
if you always want to travel back to the main fragment then you want to only add the main fragment to the backstack that way on pressing the back button you will always land there
in this part of your oncreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_what);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mToggle=new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
fragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_content,new mainfrag());
//HERE YOU PUT THE CODE V
fragmentTransaction.addToBackStack(null);
//HERE YOU PUT THE CODE ^
fragmentTransaction.commit();
ActionBar actionBar= getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// ALL THE OTHER STUFF COMMING AFTER
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.