大家好我有一个带有两个文本框的警告框,这里的问题是当用户点击弹出窗口之外时警报对话框消失,或者当用户点击确定按钮时警报对话框消失。
所以请在这方面帮助我 提前谢谢......
final AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Sign In Failed");
final EditText input1=new EditText(MainActivity.this);
final EditText input2=new EditText(MainActivity.this);
input1.setHint("eNTER name1");
input2.setHint("Enter Name2");
LinearLayout linearLayout= new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
builder.setMessage("Invalid username or password");
linearLayout.addView(input1);
linearLayout.addView(input2);
builder.setView(linearLayout);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
答案 0 :(得分:2)
你需要设置外部触摸假试试这个:
setCanceledOnTouchOutside(false);
答案 1 :(得分:1)
只需设置cancelable false:
.setCancelable(false)
答案 2 :(得分:1)
因为默认情况下它是可取消的
在builder.setView(linearLayout) -
之后添加builder.setCancelable(false);
<强>更新强>
根据您的代码段 -
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
在正面按钮上(&#34;确定&#34;)点击,您正在设置dialog.cancel()
不要这样做,您应该按照正面按钮点击的要求设置一些操作。
请参阅:
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel(); // close the current dialog
}
});
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Perform any Intent Action or perform validation as you want
}
});
更新2
只需复制&amp;粘贴下面的代码 - 完美地工作
final EditText input1 = new EditText(MainActivity.this);
final EditText input2 = new EditText(MainActivity.this);
input1.setHint("Enter name1");
input2.setHint("Enter Name2");
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.addView(input1);
linearLayout.addView(input2);
final AlertDialog builder = new AlertDialog.Builder(MainActivity.this)
.setTitle("Sign In Failed")
.setCancelable(false)
.setMessage("Invalid username or password").setView(linearLayout).setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
builder.show();
builder.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (input1.length() <= 0) {
Toast.makeText(MainActivity.this, "Please Enter Name", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "OK", Toast.LENGTH_SHORT).show();
builder.dismiss();
}
}
});