Java Android:按下后退按钮时提示用户保存更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2459848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:01:19  来源:igfitidea点击:

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

javaandroid

提问by chriskopec

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 changes have been made that have not yet been saved. After reading through the android documentation, it seems like this piece of code should go in the onPause method. I've tried putting an AlertDialog in the onPause however the dialog gets shown and then immediately tears down because nothing is there to block the pause from completing.

我有一个包含多个用户可编辑项目(EditText 字段、RatingBar 等)的活动。如果按下后退/主页按钮并且进行了尚未保存的更改,我想提示用户。通读android文档后,这段代码似乎应该放在onPause方法中。我试过在 onPause 中放置一个 AlertDialog,但是对话框被显示,然后立即拆除,因为没有什么可以阻止暂停完成。

This is what I've come up with so far:

这是我到目前为止想出的:

@Override
protected void onPause() {
    super.onPause();

    AlertDialog ad = new AlertDialog.Builder(this).setMessage(
            R.string.rating_exit_message).setTitle(
            R.string.rating_exit_title).setCancelable(false)
            .setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            // User selects OK, save changes to db
                        }
                    }).setNeutralButton(android.R.string.cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) {
                            // User selects Cancel, discard all changes
                        }
                    }).show();
}

Am I on the right track or is there another way to accomplish what I'm trying to do here? Any help would be great!

我是在正确的轨道上还是有另一种方法来完成我在这里要做的事情?任何帮助都会很棒!

采纳答案by Dan Lew

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:

你不是在正确的轨道上;您应该做的是覆盖onKeyDown()和侦听后退键,然后覆盖默认行为:

@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:

如果您只支持 Android 2.0 及更高版本,他们已经添加了一个onBackPressed()您可以使用的:

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

This answer is essentially ripped from this blog post. Read it if you need longpresses, compatibilitysupport, support for virtual hardkeys, or rawsolutions like onPreIme()etc.

这个答案基本上是从这篇博客文章中撕下来。如果您需要按、兼容性支持、虚拟硬键支持或原始解决方案onPreIme()等,请阅读它 。

回答by Oxydant

What do you think about this approach ..

您如何看待这种方法..

private  void exit(){
    this.finish();
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

        AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
        alertbox.setTitle("Message");
        alertbox.setMessage("Quit ??? ");

        alertbox.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        exit();
                    }
                });

        alertbox.setNeutralButton("No",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                });

        alertbox.show();

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

}

回答by danigonlinea

I am doing the same thing that you do. I have one activity with a customer information (EditText for name, last name, email, ..., you know, EditText everywhere) and I used AsyncTask for that, and it works wonderfully.

我正在做和你一样的事情。我有一个关于客户信息的活动(姓名、姓氏、电子邮件、...的 EditText,你知道,到处都是 EditText),我使用了 AsyncTask,它工作得非常好。

    @Override
public void onBackPressed() 
{
            // start async task for save changes.
    new GuardandoContactoHilo().execute()
}

public void VolverAtras()
{
    super.onBackPressed();
}

public class GuardandoContactoHilo extends AsyncTask< Void, Void, Void> 
{

     private ProgressDialog saving;


    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        saving = new ProgressDialog(cont);

        saving.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        saving.setMessage("Saving customer ...");
        saving.show();
    }

    @Override
    protected void onPostExecute(Void result) 
    {
        super.onPostExecute(result);
        saving.dismiss();
        VolverAtras(); // go back !!
    }

    @Override
    synchronized protected Void doInBackground(Void... arg0) 
    {

        // do what you want to do before come back ! for example, save data ;)
        return null;
    }

}

回答by live-love

Here is some sample code:

下面是一些示例代码:

@Override
public void onBackPressed() {       
    if (isDirty) {          
        new AlertDialog.Builder(this)
            .setTitle("You have made some changes.")
            .setMessage("Would you like to save before exiting?")
            //.setNegativeButton(android.R.string.no, null)            
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    MyActivity.super.onBackPressed();
                }
            })            
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {                    
                    if (Save())
                        MyActivity.super.onBackPressed();
                }
            }).create().show();
    }
    else {
        MyActivity.super.onBackPressed();
    }
}