Question

I didn't want to make the title to long so I will expand on it here. I have a fragment(called Signatures), when I press the back button in that fragment I want to call a method to save the data of the controls(EditText fields etc). So therefore I implemented an OnKeyListener() so that I can call my save method. This is what my keyListener looks like.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    context = getActivity();

    textFields = new ArrayList<EditText>();//These will store my dynamically generated controls
    signatures = new ArrayList<DrawingView>();//These will store my dynamically generated controls

    view = inflater.inflate(R.layout.signatures, container, false);


    view.setFocusableInTouchMode(true);
    view.requestFocus();
    view.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if( keyCode == KeyEvent.KEYCODE_BACK )
            {
                storeData();//This method will save all the data

                getFragmentManager().popBackStack("signature", FragmentManager.POP_BACK_STACK_INCLUSIVE);
                return true;
            }
            else
            {
                return false;
            }
        }
    });

    //Create the main layout
    RelativeLayout mainLayout = (RelativeLayout)view.findViewById(R.id.mainLayout);

    //Dynamically generate the layout
    setupPage(mainLayout);

    return view;
}

So here is the problem. I will click next on the previous fragment which will start this fragment(Signatures). The fragment will launch no problem with no keyboard popup. If I press the back button, it will launch the keyListener code no problem. BUT, as soon as I click on an EditText and the keyboard pops up, if I press back to clear the keyboard nothing happens(meaning the keyListener code doesn't get executed which makes sense). This doesn't worry me, but when I press back the second time to go back to the previous fragment, the code doesn't get executed. I believe there is a deeper understanding to this which I can't seem to figure out.

Was it helpful?

Solution

Fragments are managed by the Fragment Managers which are called by the Activity; so, to control what you want to do when the back button is clicked, you must do that in the activity;

Now, if you have more than one fragment set, you should use tags to find them, check to see if they are visible and if so, do what you mentioned above.

When setting your fragments, you should give them a tag and then use this tag later to findFragmentByTagName() and do an if check to see which fragment is set at the moment; Let me know if you need more help.

I hope this helped!

OTHER TIPS

Try using

@Override
public void onBackPressed() {
    // do something on back.
    return;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top