Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyEvent.KEYCODE_BACK getting called twice in Fragment

I am calling KeyEvent.KEYCODE_BACK on my View in my fragment and for some odd reason it gets called twice.

I have no idea as to why it is behaving this way.

Here is my fragment:

    @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    myFragmentView = inflater.inflate(R.layout.folders, container, false);

    myFragmentView.setFocusableInTouchMode(true);
    myFragmentView.requestFocus();
    myFragmentView.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub

            if (keyCode == KeyEvent.KEYCODE_BACK) {

                String parent = file.getParent().toString();
                file = new File(parent);
                File list[] = file.listFiles();

                myList.clear();

                for (int i = 0; i < list.length; i++) {
                    myList.add(list[i].getName());
                }
                Toast.makeText(getActivity(), parent, Toast.LENGTH_LONG)
                        .show();
                setListAdapter(new ArrayAdapter<String>(getActivity(),
                        android.R.layout.simple_list_item_1, myList));

            }

            return true;

        }
    });

    return myFragmentView;
}
like image 337
Jack Avatar asked Mar 11 '15 22:03

Jack


1 Answers

It is correct that onKey would be called twice, one for a Down event and another one for an Up event. Please try to add a condition:

if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
    ...
}

Hope it helps.

like image 96
nuuneoi Avatar answered Nov 01 '22 11:11

nuuneoi