android 自定义按钮实现 home键 和返回键

本文详细介绍了手机应用中如何实现返回与退出功能,包括使用Intent切换到home页面、监听返回键并弹出确认对话框,以及自定义退出对话框的实现方式。

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

转自:点击打开链接

由于在自己做的东西中用到了就总结一下,自己做了测试 在一个程序运行中如果按 返回键  分别执行了 : onpause()     onStop()   onDestory()方法    

 如果点击 home键 则执行了  onPause()   onStop()方法  ,呵呵这个方法的介绍可以在以后写程序中在不同的方法中执行不同的方法

 下边是实现两个按钮了


1.实现home键   

    Intent intent = new Intent(Intent.ACTION_MAIN);  
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 注意,这个地方最重要,关于解释,自己google吧  
                intent.addCategory(Intent.CATEGORY_HOME);  
                this.startActivity(intent);  

2.实现返回键

     1)监听返回键动作

// 退出时提示  
public boolean onKeyDown(int keyCode, KeyEvent event) {  
    if (keyCode == KeyEvent.KEYCODE_BACK) {  
        AlertDialog.Builder mDialog = new AlertDialog.Builder(  
                locResource.this);  
        mDialog.setTitle("操作提示");  
        mDialog.setMessage("确定退出吗?");  
        mDialog.setPositiveButton("确定",  
                new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int which) {  
                        System.exit(0);  
                    }  
                });  
        mDialog.setNegativeButton("取消", null);  
        mDialog.show();  
    }  
    return super.onKeyDown(keyCode, event);  
 2)自己写按钮实现方法
    AlertDialog.Builder mDialog = new AlertDialog.Builder(mainActivity.this);  
        mDialog.setTitle("退出");  
        mDialog.setMessage("确定要退出吗?");  
        mDialog.setPositiveButton("确定",  
                new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog, int which) {  
                        System.exit(0);  
                    }  
                });  
        mDialog.setNegativeButton("取消", null);  
        mDialog.show();  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值