android弹出对话框时对返回键的监听细节

当Android应用显示进度条对话框时,监听并响应返回键以优雅地返回上一Activity的详细实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在程序执行到一个进度条对话框,如果需要点击手机上的返回键想回到上一个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;
		
	}

*/
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值