How do I clear EditText after all fragments above it have been popped?

ε祈祈猫儿з 提交于 2019-12-12 05:29:04

问题


In an Android project, I have 3 fragments, and I navigate through them during an operation the user does.

FragmentA -> FragmentB -> FragmentC

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);
    }

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.

Is there a way to know that the fragment has been popped and reset that EditText?

EDIT

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);
}

回答1:


This can be easily done using flags.

The idea is that when the popBackStack() is called, the Activity sets a flag which will be checked by FragmentA in its onResume().

Simplified steps:

  1. When popping off FragmentC, do this:

    clearEditTextOfA = true;
    
  2. in onResume() of FragmentA, do this:

    if (activityCallback.shouldClearEditText()) {
        editText.setText("");
    }
    

    The activityCallback is an interface which lets a Fragment communicate with the Activity it is placed in. See Android Docs.

  3. Instead of doing ft.add(), do ft.replace().

    This will make the onResume() of your Fragments get called whenever they change.



来源:https://stackoverflow.com/questions/45192417/how-do-i-clear-edittext-after-all-fragments-above-it-have-been-popped

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!