问题描述
在一个Android项目中,我有3个片段,并在用户执行操作时浏览它们.
In an Android project, I have 3 fragments, and I navigate through them during an operation the user does.
当用户完成操作后,我执行popBackStack
返回FragmentA
When the user finishes the operation, I do a popBackStack
to return to FragmentA
if(getFragmentManager()!=null)
if(getFragmentManager().getBackStackEntryCount()>0) {
getFragmentManager().popBackStack(getFragmentManager()
.getBackStackEntryAt(0)
.getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
我的问题是:
我有一个EditText
,用户在其中编写一些文本,并且在调用popBackStack()
之后,该片段仍显示文本.
My question is:
I have an EditText
, where the user writes some text, and after the call to popBackStack()
, the fragment shows with the text still there.
是否有办法知道片段已弹出并重置EditText
?
Is there a way to know that the fragment has been popped and reset that EditText
?
这是我用来转到下一个屏幕的方法:
This is what I use to go to next screen:
try {
String backStateName = ((Object) fragment).getClass().getName();
String fragmentTag = backStateName;
ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_NONE);
if (addToBackStack)
ft.addToBackStack(backStateName);
ft.commit();
} catch (Exception e) {
Logging.logException(e);
}
推荐答案
使用标记可以轻松完成此操作.
This can be easily done using flags.
这个想法是,当调用popBackStack()
时,活动将设置一个标志,FragmentA将在其onResume()
中对其进行检查.
The idea is that when the popBackStack()
is called, the Activity sets a flag which will be checked by FragmentA in its onResume()
.
简化步骤:
-
弹出FragmentC时,请执行以下操作:
When popping off FragmentC, do this:
clearEditTextOfA = true;
在FragmentA的onResume()
中的
中,执行以下操作:
in onResume()
of FragmentA, do this:
if (activityCallback.shouldClearEditText()) {
editText.setText("");
}
activityCallback
是使Fragment与它所放置的Activity通信的接口.请参见 Android文档.
The activityCallback
is an interface which lets a Fragment communicate with the Activity it is placed in. See Android Docs.
执行ft.replace()
,而不是执行ft.add()
.
这将使您的片段的onResume()
每当它们更改时都会被调用.
This will make the onResume()
of your Fragments get called whenever they change.
这篇关于弹出所有上方的片段后,如何清除EditText?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!