Using onBackPressed () with backward compatibility

I want to use the onBackPressed () method and still want to provide support for the Android SDK up to 2.0. onBackPressed () introduced in Android SDK 2.0. but how to do that?

+3
source share
3 answers

Using onKeyDown;

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

          // Your Code Here

        return true;
    }
    return super.onKeyDown(keyCode, event);
}
+8
source

You can capture the key event and check the return key. About your activity:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK){
        goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

And write a goBack method to go where you need to.

More: Android - onBackPressed () not working

+4
source

--- > http://apachejava.blogspot.com/2011/01/backward-compatibility-using.html

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
            && keyCode == KeyEvent.KEYCODE_BACK
            && event.getRepeatCount() == 0) {
        // Take care of calling this method on earlier versions of
        // the platform where it doesn't exist.
        onBackPressed();
    }

    return super.onKeyDown(keyCode, event);
}

@Override
public void onBackPressed() {
    // This will be called either automatically for you on 2.0
    // or later, or by the code above on earlier versions of the
    // platform.
    return;
}
+1

Source: https://habr.com/ru/post/1788149/


All Articles