Android Fragment回退
阿新 • • 發佈:2019-02-20
假設場景:登入、註冊
MainActivity初始化和監聽返回鍵
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getSupportFragmentManager();
addFragment(new LoginFragment(), "login" );
}
public void addFragment(Fragment fragment, String tag) {
FragmentTransaction beginTransaction = mFragmentManager.beginTransaction();
beginTransaction.add(R.id.login_content, fragment, tag);
// 新增到回退棧,並定義標記
beginTransaction.addToBackStack(tag);
beginTransaction.commit();
}
/**
* 監聽返回鍵
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// 獲取當前回退棧中的Fragment個數
int backStackEntryCount = mFragmentManager.getBackStackEntryCount();
// 回退棧中至少有多個fragment,棧底部是首頁
if (backStackEntryCount > 1 ) {
// 回退一步
mFragmentManager.popBackStackImmediate();
// 獲取當前退到了哪一個Fragment上,重新獲取當前的Fragment回退棧中的個數
FragmentManager.BackStackEntry backStack = mFragmentManager.getBackStackEntryAt(mFragmentManager.getBackStackEntryCount() - 1);
// 獲取當前棧頂的Fragment的標記值
String tag = backStack.getName();
if (tag.equals("login")) {
if (isLogin) {
addFragment(new LoginFragment(), "login");
isLogin = false;
} else
finish();
}
} else {
finish();
}
}
return true;
}
LoginFragment中的事件處理
@OnClick({R.id.btn_register})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.btn_register:
LoginActivity activity = (LoginActivity) getActivity();
activity.addFragment(new RegisterFragment(), "register");
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.hide(getActivity().getSupportFragmentManager().findFragmentByTag("login"));
fragmentTransaction.commit();
break;
}
}
RegisterFragment中的事件處理
@OnClick({R.id.btn_back})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.btn_back:
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.show(getActivity().getSupportFragmentManager().findFragmentByTag("login"));
fragmentTransaction.hide(getActivity().getSupportFragmentManager().findFragmentByTag("register"));
fragmentTransaction.commit();
break;
}
}