在同一活动中替换片段时,我面临一种奇怪的行为,发生了什么:
-我有一个signinFragment
,它是AhuthenticationActivity
中的默认片段。
-我有一个界面,可以在单击signUp
之类的按钮时在片段之间切换。
-我在Activity中实现接口,并检查为接口函数传递的数字,然后打开指定的片段。
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
ButterKnife.bind(this, rootView);
signInButton.setOnClickListener(view-> startActivity(new Intent(getActivity(), MainActivity.class)));
signUpTextView.setOnClickListener(view-> listener.switchFragment(Constants.SIGNUP_FRAGMENT));
forgetPasswordTextView.setOnClickListener(view-> listener.switchFragment(Constants.FORGET_PASSWORD_FRAGMENT));
return rootView;
}
@Override
public void switchFragment(int fragment) {
switch (fragment){
case Constants.SIGNUP_FRAGMENT: {
Log.d(TAG,"SignUP Launched"); // this shows SignUP Launched
//ForgetPassword Launched i don't know why?!
fragmentManager.beginTransaction().replace(R.id.Authentication_Activity_Container, signUpFragment).addToBackStack(TAG).commit();
}case Constants.FORGET_PASSWORD_FRAGMENT:{
Log.d(TAG,"ForgetPassword Launched"); //this works fine ForgetPassword Launched
fragmentManager.beginTransaction().replace(R.id.Authentication_Activity_Container, forgetPasswordFragment).addToBackStack(TAG).commit();
}
}
}
@Override
public void onBackPressed() {
if(fragmentManager.getBackStackEntryCount()>0){
fragmentManager.popBackStack(TAG, POP_BACK_STACK_INCLUSIVE);
}else {
super.onBackPressed();
}
}
所以发生的事情是,当我单击signUp
时Log
依次显示signUp Launched
和ForgetPassword Launched
,而当我单击forgetPassword
时Log
显示ForgetPassword Launched
,我不知道为什么会这样?
答案 0 :(得分:1)
您错过了开关盒之间的中断。
您的最后一个代码块应为:
@Override
public void switchFragment(int fragment) {
switch (fragment){
case Constants.SIGNUP_FRAGMENT: {
Log.d(TAG,"SignUP Launched"); // this shows SignUP Launched
//ForgetPassword Launched i don't know why?!
fragmentManager.beginTransaction().replace(R.id.Authentication_Activity_Container, signUpFragment).addToBackStack(TAG).commit();
}
break;
case Constants.FORGET_PASSWORD_FRAGMENT:{
Log.d(TAG,"ForgetPassword Launched"); //this works fine ForgetPassword Launched
fragmentManager.beginTransaction().replace(R.id.Authentication_Activity_Container, forgetPasswordFragment).addToBackStack(TAG).commit();
}
}
}
@Override
public void onBackPressed() {
if(fragmentManager.getBackStackEntryCount()>0){
fragmentManager.popBackStack(TAG, POP_BACK_STACK_INCLUSIVE);
}else {
super.onBackPressed();
}
}