Back弹出AlertDialog

package com.pingyijinren.helloworld.activity;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

import com.pingyijinren.helloworld.R;
public class MainActivity extends AppCompatActivity {
    private AlertDialog alertDialog;
    private CharSequence[] data=new CharSequence[]{"香蕉","苹果","桃子"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK){
            AlertDialog.Builder builder=new AlertDialog.Builder(this);
            builder.setIcon(R.mipmap.ic_launcher);
            builder.setTitle("程序退出?");
//            builder.setMessage("确定退出吗?");
            builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.setSingleChoiceItems(data, 0, new DialogInterface.OnClickListener() {  //其实就是setMessage
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Toast.makeText(MainActivity.this,data[which],Toast.LENGTH_SHORT).show();
                }
            });
            alertDialog=builder.create();
            alertDialog.show();
        }
        return super.onKeyDown(keyCode, event);
    }
}

 

posted @ 2016-06-02 14:45  zqxLonely  阅读(185)  评论(0编辑  收藏  举报