Android:如何处理onBackPressed嵌套片段 [英] 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
当显示activity
加载fragment1.view1
时,如果发生某些用户交互View 1 close and View 2 Open
(将其视为2张卡,则其中一张被隐藏,另一张被显示).从back press
的View 1
用户应该回到View 1
.这变得比我想象的更令人头疼.我能想到的最好的方法是override activity.onBackPressed()
,检查containerFragment
当前是否不是null
并调用containerFragment.onBackPressed()
(自定义方法),然后检查fragment1
不是null
并调用view 2
是否显示,如果是,则关闭View 2
并显示view 1
. android
中有没有更简单的方法来解决这样的问题?我无法控制应用程序这一部分的结构.
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). From View 1
on back press
user should back to 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
. Is there any simpler way in android
to solve a problem like this? I don't have control over restructuring this part of the app.
摘要:我在另一个包含两个views
的fragment
中有一个fragment
,我想在backpressed
上从view 2
转到view 1
Summary: I have a fragment
inside another fragment
which contains 2 views
, I want to on backpressed
go from view 2
to view 1
推荐答案
我将实现一个名为FragmentViewController
的东西,它可以在Fragment中显示正确的视图.真的很简单,例如
I'd implement something called FragmentViewController
which would be responsible for display proper view in your 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; }
}
根据状态 (FragmentViewController
)在片段中显示视图.每次状态更改后,刷新Fragment以显示正确的视图.
Show view in your Fragment based on state of FragmentViewController
. After each change of state refresh Fragment to show proper view.
当显示view2时,调用setSecondView()
.
在活动中覆盖onBackPressed
,并管理FragmentViewController
的状态以处理后退按钮,例如:当view2显示时,调用setFirstView
来还原Fragment中的第一个视图.
When view2 will be show, call 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.
这篇关于Android:如何处理onBackPressed嵌套片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!