所以我有以下AppCompatDialogFragment。我希望我的positiveButton关闭对话框,除非某些条件为真。我不知道如何实现这一目标。
public class ColorPicker extends AppCompatDialogFragment {
private EditText editTextCode;
private ColorPickerListener listener;
/*other stuff*/
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.color_picker, null);
builder.setView(view);
builder.setTitle("Enter HEX code");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String code = editTextCode.getText().toString();
if(code.length() != 6 && !code.matches("[0-9A-F]+")){
//HERE I WANT TO PREVENT THE DIALOG FROM CLOSING!!
}
listener.applyHex(code);
}
});
/* ... */
return builder.create();
}
答案 0 :(得分:3)
您可以通过覆盖正面按钮的OnClickListener
来实现它,如下所示
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String code = editTextCode.getText().toString();
if(code.length() != 6 && !code.matches("[0-9A-F]+")){
//Don't dismiss
} else{
dialog.dismiss();
}
}
});
注意:强>
请务必在调用dialog.show()
后执行此操作,否则最终会获得NullPointerException
。
由于您使用AppCompatDialogFragment
,因此onResume()
的{{1}}
ColorPicker
答案 1 :(得分:0)
@Override
public void onResume()
{
super.onResume();
final AlertDialog d = (AlertDialog)getDialog();
if(d != null)
{
Button positiveButton = (Button) d.getButton(Dialog.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
//your conditions are here
}
});
}
}
并且setPositiveButtonclick
onCreateDialog
内的任何内容都不执行任何操作
答案 2 :(得分:0)
实际上,你只需要在正面按钮点击事件中获得对话界面就没有什么需要做的了,你只需要在你的其他情况下放下代码来解雇,如下文
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String code = editTextCode.getText().toString();
if(code.length() != 6 && !code.matches("[0-9A-F]+")){
//HERE I WANT TO PREVENT THE DIALOG FROM CLOSING!!
}else {
dialog.dismiss();
}
if(listener!=null){
listener.applyHex(code);}
}
});