Android AlertDialog工具类 实现对话框回调

   AlertDialog工具类

import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;

public class DialogUtil {

    private static AlertDialog dialog;

    //回调接口
    public interface ResultCallBack {
        public void callback(boolean flag);
    }

    public static void showDialog(Context context, String str, final ResultCallBack resultCallBack) {
        dialog = new AlertDialog.Builder(context)
                .setTitle("提示")
                .setMessage(str)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (resultCallBack!= null) {
                            resultCallBack.callback(true);
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (resultCallBack!= null) {
                            resultCallBack.callback(false);
                        }
                    }
                }).create();
//        dialog.setCancelable(false); //dialog弹出后会点击屏幕或物理返回键,dialog不消失
        dialog.setCanceledOnTouchOutside(false);//dialog弹出后会点击屏幕,dialog不消失;点击物理返回键dialog消失
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {//屏蔽搜索键
                    return true;
                } else {
                    return false; //默认返回 false
                }
            }
        });
        dialog.show();
    }
    
}

   调用实例

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.lorytech.lmsapp.utils.DialogUtil;

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DialogUtil.showDialog(this, "提示内容", new DialogUtil.ResultCallBack() {
            @Override
            public void callback(boolean flag) {
                if (flag) {
                    Toast.makeText(getApplicationContext(), "确定操作", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), "取消操作", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

 

 

你可能感兴趣的:(android)