Ryan Ryan - 7 days ago 6
Android Question

The method onKeyDown(int, KeyEvent) is undefined for the type Fragment

I am trying to detect if the back button was pressed in one of my Fragments using onKeyDown but I get the error


The method onKeyDown(int, KeyEvent) is undefined for the type Fragment


at the end of the function. Is there a way to use this function in Fragments?

public class FragmentStory4 extends Fragment {
public FragmentStory4 () {

}

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

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

return view;
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {

}
return super.onKeyDown(keyCode, event);
}
}

Answer

Try this and tell me :)

fragment.getView().setOnKeyListener( new OnKeyListener()
{
    @Override
    public boolean onKey( View v, int keyCode, KeyEvent event )
    {
        if( keyCode == KeyEvent.KEYCODE_BACK )
        {
            return true;
        }
        return false;
    }
} );