活动中的后退按钮行为会在底部导航视图中破碎

时间:2018-07-26 09:46:17

标签: android android-fragments bottomnavigationview fragment-backstack

我有一个bottomnavigationview,其中包含5个片段,(考虑A(家庭),B,C,D,E)如果我去片段D,然后去活动(哪个在片段D或C或任何片段中) 5),然后按设备的后退按钮。它直接进入Home片段(A),实际上,它应该进入片段D或C。 我在上一个项目中使用过botomnavigationview,但是一切正常。

正在发生-MainActivity + HomeFragment(A)---> Fragment D->> Activity --- >> OnbackPressed --- >> HomeFragment

预期-MainActivity + HomeFragment(A)--->片段D->> Activity --- >> OnbackPressed --- >> D片段

感谢您的帮助。

片段D代码类似

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));
            }
        }
    });

活动代码是这样的

@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();
}

}

主要活动就是这样

      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`

2 个答案:

答案 0 :(得分:1)

注意,请使用!在回答中说,添加片段代替 YOLO 您可以获取堆栈计数并在您的算法支持下使用它

好吧,我不是这是做自己喜欢的事情的最好方法!但它仍然可以帮助您。在您的mainActivity中,您的底部导航位置是!有全局声明和初始化!并在onResume方法中执行类似的操作! 您可以使用清空或检查碎片堆!

if (getSupportFragmentManager().getBackStackEntryCount() > 0 ){
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }

在您的onResume中做类似的事情!在底部导航的getItem中传递所需的项目编号(#position)!

@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);
 }

答案 1 :(得分:0)

使用以下代码替换代码:

 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.setCustomAnimations(R.anim.fadein, R.anim.fadeout);
                transaction.replace(R.id.home_container, fragment);
                transaction.addToBackStack(fragmentName)
                transaction.commit();