using onBackPressed() with backward compatibility

大憨熊 提交于 2019-12-09 13:42:20

问题


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


回答1:


Using onKeyDown;

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

          // Your Code Here

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



回答2:


You may capture a key event and check for the back key. On 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 the goBack method to go where you need.

More at: Android - onBackPressed() not working




回答3:


Answer ---> 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;
}


来源:https://stackoverflow.com/questions/4815127/using-onbackpressed-with-backward-compatibility

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!