Android开发之对话框事件之点击手…

点击手机上的退出按钮,实现退出警告框的实现
Android开发之对话框事件之点击手机推出按钮实现推出警告


.xml文件

     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <ImageButton 
        android:id="@+id/imgbut"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/exit"/>

</LinearLayout>


.java文件

package com.example.dialogdemo;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class MainActivity extends Activity {
private ImageButton imgButton=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imgButton=(ImageButton) super.findViewById(R.id.imgbut);
//为我们的图片添加事件
this.imgButton.setOnClickListener(new OnClickListenerImp());
}
public class OnClickListenerImp implements OnClickListener{

public void onClick(View arg0) {
MainActivity.this.exitDialog();
}
}
//退出的方法
public void exitDialog(){
Dialog dialog=new AlertDialog.Builder(MainActivity.this)
.setTitle("程序退出?")
.setMessage("您要退出吗")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//确定的话就表示退出,此时我们结束我们程序
//使用我们Activity提供的finish方法
MainActivity.this.finish();//操作结束
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.create();
dialog.show();
}

//此方法用来实现,用户按下返回按钮出现警告提示
public boolean onKeyDown(int keyCode, KeyEvent event) {
//如果用户按下手机上的返回键,出现提示
if(keyCode==KeyEvent.KEYCODE_BACK){
this.exitDialog();
}
return false;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值