当弹出进度对话框时,如何处理android上的"后退按钮"

mic*_*ael 5 android

当我的android活动弹出一个进度对话框时,用户单击后退按钮时处理的正确方法是什么?

谢谢.

And*_*wKS 12

创建一个扩展ProgressDialog的新对话框对象,然后覆盖其中的public void onBackPressed()方法.


chi*_*ich 6

if your not having any luck with the onCancel() method, than you can either write up a onKeyDown() method in your activity to check if the progress dialog is showing and if the back button is pressed...or you can override the onBackPressed() method (again, for the activity) and check if your dialog is showing. alternatively you can extend the ProgressDialog class and override onBackPressed() directly from there...in which case you wouldnt have to check if the dialog is showing.

eg. for activity method:

public void onBackPressed()
{
    if (progressDialog.isShowing())
    {
        // DO SOMETHING
    }
}
Run Code Online (Sandbox Code Playgroud)

onKeyDown()方法类似,但你必须检查对话框是否显示,按下的按钮是否是"后退"按钮,你还应该调用super.onKeyDown()来确保默认方法也会执行.

public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if (keyCode == KeyEvent.KEYCODE_BACK && progressDialog.isShowing())
    {
        // DO SOMETHING
    }

    // Call super code so we dont limit default interaction
    super.onKeyDown(keyCode, event);

    return true;
}
Run Code Online (Sandbox Code Playgroud)

使用任一方法,progressDialog变量/属性显然必须在范围内并且可访问.