Android: Prompt user to save changes when Back button is pressed

前端 未结 4 638
遇见更好的自我
遇见更好的自我 2020-11-27 04:45

I have an activity that contains several user editable items (an EditText field, RatingBar, etc). I\'d like to prompt the user if the back/home button is pressed and change

4条回答
  •  一个人的身影
    2020-11-27 05:36

    You're not quite on the right track; what you should be doing is overriding onKeyDown() and listening for the back key, then overriding the default behavior:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            // do something on back.
            return true;
        }
    
        return super.onKeyDown(keyCode, event);
    }
    

    If you're only supporting Android 2.0 and higher, they've added an onBackPressed() you can use instead:

    @Override
    public void onBackPressed() {
        // do something on back.
        return;
    }
    

    This answer is essentially ripped from this blog post. Read it if you need long presses, compatibility support, support for virtual hard keys, or raw solutions like onPreIme() etc.

提交回复
热议问题