Android Fragment回退
【摘要】
假设场景:登录、注册
MainActivity初始化和监听返回键
@Override
protected void onCreate(Bundle savedInstanceState...
假设场景:登录、注册
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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
文章来源: blog.csdn.net,作者:yechaoa,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/yechaoa/article/details/80370231
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)