Ryan Ryan - 1 year ago 122
Android Question

How to fix onKeyDown(int, KeyEvent) is undefined for the type Fragment error in Android?

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,

return view;

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

return super.onKeyDown(keyCode, event);

Answer Source

Try this and tell me :)

fragment.getView().setOnKeyListener( new OnKeyListener()
    public boolean onKey( View v, int keyCode, KeyEvent event )
        if( keyCode == KeyEvent.KEYCODE_BACK )
            return true;
        return false;
} );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download