I successfully implemented a bottom navigation drawer and had used fragments. Now i can switch fragments from the drawer menu. My problem here is that when I open an item from the drawer menu (example; About Developer), when the user clicks the back button it closes the app. Instead i want the user to return to the Main Activity from any fragment. Help me with this, I don't have much experience.
Here is my code;
How i implement the nav drawer items using drawer adapter with a custom library(SlidingRootNav- https://github.com/yarolegovich/SlidingRootNav);
@Override
public void onItemSelected(int position) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
if (position == POS_DASHBOARD){
slidingRootNav.closeMenu();
transaction.addToBackStack(null);
transaction.commit();
}
else if (position == POS_ABOUT_APP){
((CoordinatorLayout)findViewById(R.id.root_view)).removeAllViews();
AboutAppFragment aboutApp = new AboutAppFragment();
transaction.replace(R.id.container, aboutApp);
slidingRootNav.closeMenu();
transaction.addToBackStack(null);
transaction.commit();
}
else if (position == POS_ABOUT_DEVELOPERS){
((CoordinatorLayout)findViewById(R.id.root_view)).removeAllViews();
AboutDeveloper aboutDeveloper = new AboutDeveloper();
transaction.replace(R.id.container, aboutDeveloper);
slidingRootNav.closeMenu();
transaction.addToBackStack(null);
transaction.commit();
}
}
Fragment Class
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AboutDeveloper extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_about_developer,container, false);
// Here I implemented a toolbar at the top for navigation purpose
// but on clicking on the nav icon, the app closes, instead i want to return to the main activity
Toolbar toolbar = root.findViewById(R.id.return_home);
toolbar.setNavigationIcon(R.drawable.ic_baseline_arrow_back_24);
toolbar.setTitle("About Developer");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
return root;
}
}