在程序执行到一个进度条对话框,如果需要点击手机上的返回键想回到上一个activity,则需要这样处理:
package com.gem.hsx.progress;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
public class TestBack extends Activity {
ProgressDialog mypDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progressdialog_background);
mypDialog=new ProgressDialog(TestBack.this);
mypDialog.setIndeterminate(false);
mypDialog.setCanceledOnTouchOutside(false);
mypDialog.setTitle("加载中");
mypDialog.setButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
});
// mypDialog.setIndeterminate(false);//设置ProgressDialog 的进度条是否不明确;
mypDialog.setIndeterminateDrawable(getResources().getDrawable(R.anim.loading));
mypDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (keyCode== KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN)
{
if (mypDialog!=null&&mypDialog.isShowing())
{
//此句加上之后先关闭对话框,然后跳转,不加则直接跳转
//mypDialog.dismiss();
Intent intent=new Intent();
intent.setClass(TestBack.this, Main.class);
startActivity(intent);
TestBack.this.finish();
}
}
return true;
}
});
mypDialog.show();
}
/** 重写activity的方法不启用,原因是按了返回键根本不执行这个方法
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode== KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN)
{
if (mypDialog!=null&&mypDialog.isShowing())
{
//此句加上之后先关闭对话框,然后跳转,不加则直接跳转
//mypDialog.dismiss();
Intent intent=new Intent();
intent.setClass(TestBack.this, Main.class);
startActivity(intent);
TestBack.this.finish();
}
}
return true;
}
*/
}