使用具有向后兼容性的onBackPressed()

时间:2011-01-27 10:21:50

标签: android sdk

我想使用onBackPressed()方法,但仍希望在2.0之前提供对Android SDK的支持。 onBackPressed()是在Android SDK 2.0中引入的。但怎么办?

3 个答案:

答案 0 :(得分:8)

使用onKeyDown;

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

          // Your Code Here

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

答案 1 :(得分:4)

您可以捕获关键事件并检查返回键。关于你的活动:

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

并将goBack方法写入您需要的位置。

更多信息:Android - onBackPressed() not working

答案 2 :(得分:1)

答案---> 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;
}