问题
I have a bottomnavigationview
containing 5 fragments,(Consider A(Home), B, C, D, E) If I go to fragment D and then an Activity (Which is inside fragment D or C or any of 5) and press back button of the device. It is directly going to Home fragment(A), actually, it should go to fragment D or C.
I have used botomnavigationview
in my previous project but all things were working fine.
Happening-- MainActivity+HomeFragment (A)---> Fragment D-->>Activity--->>OnbackPressed--->>HomeFragment
Expected-- MainActivity+HomeFragment (A)---> Fragment D-->>Activity--->>OnbackPressed--->>D fragment
any help is appreciated.
Fragment D CODE IS LIKE THIS
public class AccountFragment extends Fragment {
public Button button;
private String TAG = AccountFragment.class.getSimpleName();
private TextView mContactustextView, mAddress, rateUs, aboutus, tvOrderHistory, userPhone, userEmail, buyerUserName, faqs;
public static AccountFragment newInstance() {
AccountFragment fragment = new AccountFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
Utils.matchColorOfStatusBar(getActivity());
View view = inflater.inflate(R.layout.accountfragment, container, false);
button = view.findViewById(R.id.login_button_account_page);
userPhone = view.findViewById(R.id.userPhone);
buyerUserName = view.findViewById(R.id.buyerUserName);
userEmail = view.findViewById(R.id.userEmail);
aboutus = view.findViewById(R.id.aboutus);
tvOrderHistory = view.findViewById(R.id.tvOrderHistory);
faqs = view.findViewById(R.id.faqs);
faqs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), FAqsActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.fadein, R.anim.fadeout);
}
});
aboutus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), AboutUsActivity.class);
startActivity(intent);
}
});
//Manage session here
if (App.getInstance().getPrefManager().isLoggedIn()) {
button.setText("Logout");
Log.e(TAG, "isWorking");
} else {
button.setText("Login");
userPhone.setText("");
userEmail.setText("");
buyerUserName.setText("");
Log.e(TAG, "isNotWorking");
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (App.getInstance().getPrefManager().isLoggedIn()) {
App.getInstance().getPrefManager().setLoginSession(false);
App.getInstance().getPrefManager().setCartCount(0);
App.getInstance().getPrefManager().setFavCount(0);
badgeCart();
badgeFav();
button.setText("Login");
userPhone.setText("");
userEmail.setText("");
buyerUserName.setText("");
Log.e(TAG, "ToLoginPage");
} else {
Intent intent = new Intent(getActivity(), LoginActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.fadein, R.anim.fadeout);
Log.e(TAG, "log");
}
}
});
//findview by id
rateUs = view.findViewById(R.id.rateus);
mAddress = view.findViewById(R.id.tv_address);
mContactustextView = view.findViewById(R.id.tv_contact_us);
rateUs.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.test.android"));
startActivity(intent);
}
});
mAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (App.getInstance().getPrefManager().isLoggedIn()) {
startActivity(new Intent(getActivity(), AddressActivity.class).putExtra("source", AccountFragment.class.getSimpleName()));
getActivity().overridePendingTransition(R.anim.fadein, R.anim.fadeout);
} else {
Utils.showAlert(getContext(), getString(R.string.please_login));
}
}
});
tvOrderHistory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (App.getInstance().getPrefManager().isLoggedIn()) {
startActivity(new Intent(getActivity(), MyOrdersListActivity.class));
getActivity().overridePendingTransition(R.anim.fadein, R.anim.fadeout);
} else {
Utils.showAlert(getContext(), getString(R.string.please_login));
}
}
});
Activity code is like this
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.matchColorOfStatusBar(this);
setContentView(R.layout.activity_contact_us);
//FindViewByIds
contact_via_call = findViewById(R.id.ll_call_custmr_care);
rootLinearLayout = findViewById(R.id.ll_contact_us);
contact_via_email = findViewById(R.id.ll_email_custmr_care);
ll_whatsapp = findViewById(R.id.ll_whatsapp);
contact_via_email.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SENDTO);
i.setData(Uri.parse("mailto:"));
i.putExtra(Intent.EXTRA_EMAIL, "");
i.putExtra(Intent.EXTRA_SUBJECT, "subject will be here");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{getString(R.string.supportemail)});
try {
ContactUsActivity.this.startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Utils.showSnakbarTypeOne(rootLinearLayout, "No email client installed");
//showAlertMessage(context, "There are no email clients installed.");
}
}
});
ll_whatsapp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openWhatsApp();
}
});
contact_via_call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String phone = getString(R.string.custmersupportnum);
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null));
startActivity(intent);
}
});
//setuptoolbar
toolbar = (Toolbar) findViewById(R.id.toolbar_contact_us);
toolbar.setTitle("Contact Us");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setTitleTextColor(getResources().getColor(R.color.white));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onBackPressed();
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
Main Activity is like this
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
fragment = HomeFragment.newInstance();
break;
case R.id.favorite:
if (App.getInstance().getPrefManager().isLoggedIn())
fragment = FavoriteFragment.newInstance();
else {
Utils.showAlert(MainActivity.this, getString(R.string.please_login));
}
break;
case R.id.categories:
fragment = CategoriesFragment.newInstance();
break;
case R.id.carts:
if (App.getInstance().getPrefManager().isLoggedIn())
fragment = CartFragment.newInstance();
else {
Utils.showAlert(MainActivity.this, getString(R.string.please_login));
}
break;
case R.id.accounts:
fragment = AccountFragment.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.fadein, R.anim.fadeout);
transaction.replace(R.id.home_container, fragment);
transaction.commit();
return true;
}
};
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void cartBadgeCount(){
BottomNavigationView mBottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
mBottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
BottomNavigationViewHelper.disableShiftMode(mBottomNavigationView);
BottomNavigationMenuView bottomNavigationMenuView =
(BottomNavigationMenuView) mBottomNavigationView.getChildAt(0);
View v = bottomNavigationMenuView.getChildAt(2);
BottomNavigationItemView itemView = (BottomNavigationItemView) v;
View badge = LayoutInflater.from(this)
.inflate(R.layout.notification_badge, bottomNavigationMenuView, false);
tvCartCount = badge.findViewById(R.id.notification_badge);
itemView.addView(badge);
mBottomNavigationView.setSelectedItemId(R.id.home);
if (Validation.isValidString(getIntent().getStringExtra(Constant.GO_TO_CART)) && getIntent().getStringExtra(Constant.GO_TO_CART).equalsIgnoreCase(Constant.GO_TO_CART)) {
// getSupportFragmentManager().beginTransaction().replace(R.id.home_container, new CartFragment()).commit();
// bottomNavigationMenuView.getSelectedItemId().setSelected(true);
View view = bottomNavigationMenuView.findViewById(R.id.carts);
view.performClick();
}
}
private void favCountBadge() {
BottomNavigationView mBottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
mBottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
BottomNavigationViewHelper.disableShiftMode(mBottomNavigationView);
BottomNavigationMenuView bottomNavigationMenuView =
(BottomNavigationMenuView) mBottomNavigationView.getChildAt(0);
View v = bottomNavigationMenuView.getChildAt(3);
BottomNavigationItemView itemView = (BottomNavigationItemView) v;
View badge = LayoutInflater.from(this)
.inflate(R.layout.notification_badge, bottomNavigationMenuView, false);
tvFav = badge.findViewById(R.id.notification_badge);
itemView.addView(badge);
}
@Override
protected void onResume() {
super.onResume();
cartBadgeCount();
favCountBadge();
if (App.getInstance().getPrefManager().getCartCount() > 0) {
tvCartCount.setVisibility(View.VISIBLE);
tvCartCount.setText(String.valueOf(App.getInstance().getPrefManager().getCartCount()));
} else
tvCartCount.setVisibility(View.GONE);
if (App.getInstance().getPrefManager().getFavCount() > 0) {
tvFav.setVisibility(View.VISIBLE);
tvFav.setText(String.valueOf(App.getInstance().getPrefManager().getFavCount()));
} else
tvFav.setVisibility(View.GONE);
Log.e(TAG, "cart count " +
String.valueOf(App.getInstance().getPrefManager().getCartCount()));
Log.e(TAG, "fav count " +
String.valueOf(App.getInstance().getPrefManager().getFavCount()));
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirmation")
.setMessage("Are you sure you want to Exit?")
.setPositiveButton("Yes", new
DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which)
{
finishAffinity();
}
})
.setNegativeButton("No", null)
.show();
}`enter code here`
回答1:
NOTE PLEASE USE!!! ADD FRAGMENT INSTEAD OF REPLACE FRAGMENT AS YOLO said in the answer you can get the stack count and use it in the favour of your algorithm
Well I don't that this is the best way to do the thing that you like! but still it can help you . in your mainActivity where your bottom navigation is ! have that global declared and initialised ! and do something like this in onResume method ! you can empty or check the stack of fragments using !
if (getSupportFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
do something like this in your onResume! pass out desired item number(#position) in the getItem of bottom navigation!
@Override
protected void onResume() {
super.onResume();
// here you can check the stack that last fragment in stack is the one that
//opened the 2nd activity then you can use its fragment to be loaded in
//transaction and also highlight the the bottomnav's tab
bottomNavigationView.getMenu().getItem(0).setChecked(true);
}
回答2:
Replace your code with following:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.fadein, R.anim.fadeout);
transaction.replace(R.id.home_container, fragment);
transaction.addToBackStack(fragmentName)
transaction.commit();
来源:https://stackoverflow.com/questions/51535870/back-button-behaviour-on-activity-to-fragment-in-bottom-navigation-view