Android dialog使用案例
需求:应用锁,
//自定义dialog的显示view
View view = getLayoutInflater().inflate(R.layout.passwd_dialog_view, null);
final EditText editText = (EditText) view.findViewById(R.id.dialog_edit);
AlertDialog dialog = new AlertDialog.Builder(this)
//.setIcon(R.mipmap.ic_launcher)//设置标题的图片
.setTitle("请输入密码")//设置对话框的标题
.setView(view)
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
})
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final String passwd = "";
String content = editText.getText().toString().trim();
if(content.equals(passwd)){
dialog.dismiss();
}else{
finish();
Toast.makeText(getApplicationContext(),"密码错误!",Toast.LENGTH_SHORT).show();
}
}
})
//关闭其他区域点击关闭dialog
.setCancelable(false)
.create();
dialog.show();
//处理Android的返回键事件
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK)
{
return true;
}
else
{
return false; //默认返回 false,这里false不能屏蔽返回键,改为true就能够了
}
}
});
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/dialog_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
></EditText>
</LinearLayout>
拓展:将dialog设置为系统级别弹窗
alertdialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
manifest配置权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>