[英]Android: how to handle onBackPressed Nested fragment
I'm in an activity with the following structure 我正在从事以下结构的活动
Activity
ContainerFragment with a view pager
fragment 1 within viewPager
View 1 inside fragment 1
View 2 inside fragment 1
When the activity
loads fragment1.view1
is shown, if some user interaction happens View 1 close and View 2 Open
(think of it as 2 cards, one gets hidden another gets shown). 当
activity
加载时,显示fragment1.view1
,如果发生某些用户交互,则View 1 close and View 2 Open
(将其视为2张卡,其中一张被隐藏,另一张被显示)。 From View 1
on back press
user should back to View 1
. 从
View 1
的back press
用户应回到View 1
。 This became more of a headache than I thought it would be. 这变得比我想象的要头痛得多。 The best I can come up with is to
override activity.onBackPressed()
, check if containerFragment
is currently not null
and call containerFragment.onBackPressed()
(custom method), which then checks if fragment1
is not null
and calls fragment1.onBackPressed()
which then checks if view 2
is showing and if yes , then close View 2
and show view 1
. 我能想到的最好的办法是
override activity.onBackPressed()
,检查containerFragment
当前是否不为null
然后调用containerFragment.onBackPressed()
(自定义方法),然后再检查fragment1
是否不为null
并调用fragment1.onBackPressed()
然后检查view 2
是否正在显示,如果是,则关闭View 2
并显示view 1
。 Is there any simpler way in android
to solve a problem like this? android
有没有更简单的方法来解决这样的问题? I don't have control over restructuring this part of the app. 我无法控制应用程序这一部分的结构。
Summary: I have a fragment
inside another fragment
which contains 2 views
, I want to on backpressed
go from view 2
to view 1
摘要:我有一个
fragment
另一个内部fragment
包含2个views
,我想在backpressed
从去view 2
至view 1
I'd implement something called FragmentViewController
which would be responsible for display proper view in your Fragment. 我将实现一个称为
FragmentViewController
东西,该东西将负责在Fragment中显示正确的视图。 It's really simple, for example 真的很简单,例如
class FragmentViewController{
private boolean firstView = true;
public boolean isFirstView() { return firstView }
public void setFirstView() { firstView = true; }
public void setSecondView() { firstView = false; }
}
Show view in your Fragment based on state of FragmentViewController
. 根据 FragmentViewController 的状态在
FragmentViewController
显示视图。 After each change of state refresh Fragment to show proper view. 每次状态更改后,刷新Fragment以显示正确的视图。
When view2 will be show, call setSecondView()
. 当显示view2时,调用
setSecondView()
。 Override onBackPressed
in your Activity, and manage the state of FragmentViewController
to handle back button pressed eg.: when view2 is showing call setFirstView
to restore first view in Fragment. 覆盖
onBackPressed
中的onBackPressed
,并管理FragmentViewController
的状态以处理后退按钮,例如:当view2显示时,调用setFirstView
以恢复Fragment中的第一个视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.