如何禁用/启用对话框负正按钮?
Posted
技术标签:
【中文标题】如何禁用/启用对话框负正按钮?【英文标题】:How to disable / enable dialog negative positive buttons? 【发布时间】:2012-01-04 13:17:43 【问题描述】:请查看下面的自定义对话框。我在对话框中有一个edittext 字段,如果文本字段为空,我想禁用positiveButton
。我可以获得文本字段的 charListener,但我不确定如何设置 positivebutton
以禁用或启用该侦听器?正面和负面按钮的参考是什么?
case DIALOG_TEXT_ENTRY:
// This example shows how to add a custom layout to an AlertDialog
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null);
return new AlertDialog.Builder(AlertDialogSamples.this)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle(R.string.alert_dialog_text_entry)
.setView(textEntryView)
.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int whichButton)
/* User clicked OK so do some stuff */
)
.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog, int whichButton)
/* User clicked cancel so do some stuff */
)
.create();
【问题讨论】:
我认为这个答案回答了你的问题 [***.com/questions/4291548/… [1]: ***.com/questions/4291548/… 谢谢,但这不是答案。不过它可能会有所帮助。因为它在单击自身后禁用按钮。这不是我想要的。我想显示它是否禁用取决于文本字段。 if(editTextEmailAddress.getText().toString().length()==0) 基本上,您正在使用匿名引用创建对象,一旦创建,您将无法再次引用它。谢谢。 【参考方案1】:if (editTextEmailAddress.getText().toString().length() == 0)
btnCancelCross.setEnabled(false);
else
btnCancelCross.setEnabled(true);
这可能对你有帮助,谢谢。
【讨论】:
谢谢,但这不是我想要的。我可以通过使用自定义对话框来完成它并使用按钮创建布局并启用禁用它们。我正在寻找的是有没有一种方法可以禁用或启用对话框的内置正面和负面按钮?如果您查看我共享的代码,您将看到我在寻找什么。但再次感谢您的代码。 请发布一个全面的主题答案(只需编辑您现有的答案,不要继续发布其他答案)。【参考方案2】:编辑完整的解决方案...
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle("Alert dialog title");
builder.setMessage("This is the example code snippet to disable button if edittext attached to dialog is empty.");
builder.setPositiveButton("PositiveButton",
new DialogInterface.OnClickListener()
public void onClick(DialogInterface arg0, int arg1)
// DO TASK
);
builder.setNegativeButton("NegativeButton",
new DialogInterface.OnClickListener()
public void onClick(DialogInterface arg0, int arg1)
// DO TASK
);
// Set `EditText` to `dialog`. You can add `EditText` from `xml` too.
final EditText input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
);
input.setLayoutParams(lp);
builder.setView(input);
final AlertDialog dialog = builder.create();
dialog.show();
// Initially disable the button
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
// OR you can use here setOnShowListener to disable button at first time.
// Now set the textchange listener for edittext
input.addTextChangedListener(new TextWatcher()
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count)
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after)
@Override
public void afterTextChanged(Editable s)
// Check if edittext is empty
if (TextUtils.isEmpty(s))
// Disable ok button
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
else
// Something into edit text. Enable the button.
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
);
以下是编辑的历史,可以参考更多的细节
这是一个示例代码,试试这个
AlertDialog.Builder builder = new AlertDialog.Builder(AddSchedule.this);
builder.setIcon(android.R.drawable.ic_dialog_info);
builder.setTitle("Alert dialog title");
builder.setMessage("Dialog message");
builder.setPositiveButton("Button1", new DialogInterface.OnClickListener()
public void onClick(DialogInterface arg0, int arg1)
//DO TASK
);
builder.setNegativeButton("Button2", new DialogInterface.OnClickListener()
public void onClick(DialogInterface arg0, int arg1)
//DO TASK
);
AlertDialog dialog = builder.create();
dialog.show();
// After calling show method, you need to check your condition and enable/disable the dialog buttons
if (your_condition_true)
// BUTTON1 is the positive button
dialog.getButton(AlertDialog.BUTTON1).setEnabled(false);
对于否定按钮
dialog.getButton(AlertDialog.BUTTON2).setEnabled(false); //BUTTON2 is negative button
按钮 id:参考alert_dialog.xml
已编辑:
自第 8 级 API (FroYo) 起,setOnShowListener 也是如此,
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.setOnShowListener(new OnShowListener()
@Override
public void onShow(DialogInterface dialog)
if (condition)
((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
);
dialog.show();
已编辑
new AlertDialog.Builder(this)
.setMessage("This may take a while")
.setPositiveButton("OK", new android.content.DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialog, int which)
((AlertDialog)dialog).getButton(which).setVisibility(View.INVISIBLE);
// the rest of your stuff
).show();
【讨论】:
如果我错了,请纠正我,但是当您再次调用 AlertDialog 时,它是再次调用它的对象还是仍然使用相同的对象。我不知道这种方法。你应该简要解释一下吗?谢谢:) 对于略读的人,我想添加 dialog.getButton() 仅适用于 AlertDialogs,因此您可能必须将对话框转换为 AlertDialog,就像您在帖子中的后续操作一样。 我不想讽刺,粗鲁。我也尝试取消投票,但这是不可能的......但是再次遇到问题 - 你的代码中哪里有文本监听器,你能告诉我吗?如果它只被调用一次,条件是什么并不重要。如果您没有像下面的尼克这样的文本侦听器,那么您的解决方案根本不可能工作......或者我错过了一些东西。或者给我发一些简单的 android 项目来证明它是有效的;) 谢谢!!!我想要这个:“((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);”你真的帮了我很多谢谢:)) 如果将所有编辑合并到一个解决方案中,这个答案会更容易理解。【参考方案3】:这些答案都不能真正解决问题。
我使用包含 EditText 和该视图上的 TextWatcher 的自定义布局来完成此操作。
final LinearLayout layout = (LinearLayout) inflator.inflate(R.layout.text_dialog, null);
final EditText text = (EditText) layout.findViewById(R.id.text_edit);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
// Now add the buttons...
builder.setPositiveButton(R.string.ok, new AlertDialog.OnClickListener()
// Left out for brevity...
builder.setNegativeButton(R.string.cancel, new AlertDialog.OnClickListener()
// Left out for brevity...
// Create the dialog
final AlertDialog d = builder.create();
// Now add a TextWatcher that will handle enable/disable of save button
text.addTextChangedListener(new TextWatcher()
private void handleText()
// Grab the button
final Button okButton = d.getButton(AlertDialog.BUTTON_POSITIVE);
if(text.getText().length() == 0)
okButton.setEnabled(false);
else
okButton.setEnabled(true);
@Override
public void afterTextChanged(Editable arg0)
handleText();
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
// Nothing to do
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
// Nothing to do
);
// show the dialog
d.show();
// and disable the button to start with
d.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
【讨论】:
这个答案不完整,没有d
的声明
已编辑以添加 d 的构造。【参考方案4】:
对于使用视图持有者从数据库列表视图中删除记录,您在 getview() 方法中使用了此代码..
viewHolder.btn.setOnClickListener(new OnClickListener()
@Override
public void onClick(View arg0)
// TODO Auto-generated method stub
AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
Favorate.this.getParent());
// Setting Dialog Title
alertDialog2.setTitle("Confirm Delete...");
// Setting Dialog Message
alertDialog2
.setMessage("Are you sure you want delete ?");
// Setting Icon to Dialog
alertDialog2.setIcon(R.drawable.delete);
// Setting Positive "Yes" Btn
alertDialog2.setPositiveButton("YES",
new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog,
int which)
// Write your code here to execute after
// dialog
int id = _items.get(position).id;
db.deleterecord(id);
db.close();
);
// Setting Negative "NO" Btn
alertDialog2.setNegativeButton("NO",
new DialogInterface.OnClickListener()
public void onClick(DialogInterface dialog,
int which)
// Write your code here to execute after
// dialog
dialog.cancel();
);
// Showing Alert Dialog
alertDialog2.show();
);
Read More
【讨论】:
【参考方案5】:这个 dialogFragment 将为您完成这项工作。请注意,屏幕旋转后对话框将保持打开状态,保留用户已经输入的任何文本。如果您不希望发生这种情况,则需要在 Activity 的 onStop 中关闭片段。 newInstance 方法签名可以更改为您需要的任何内容。
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
public class TextViewDialogFragment extends DialogFragment implements DialogInterface.OnClickListener, DialogInterface.OnShowListener, TextWatcher
final static private String TITLE = "title", MESSAGE = "message", IDENTIFIER = "identifier", INPUT_TYPE = "inputType", POSITIVE_TEXT = "pText", NEGATIVE_TEXT = "nText", CANCELABLE = "cancelable";
public TextViewDialogFragment()
super();
static public TextViewDialogFragment newInstance(int title, @Nullable String message, int identifier, int inputType, int positiveText, int negativeText, boolean cancelable)
TextViewDialogFragment fragement = new TextViewDialogFragment();
Bundle args = new Bundle();
args.putInt(TITLE, title);
args.putString(MESSAGE, message);
args.putInt(IDENTIFIER, identifier);
args.putInt(INPUT_TYPE, inputType);
args.putInt(POSITIVE_TEXT, positiveText);
args.putInt(NEGATIVE_TEXT, negativeText);
args.putBoolean(CANCELABLE, cancelable);
fragement.setArguments(args);
return fragement;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
Activity activity = getActivity();
Bundle args = getArguments();
EditText input = new EditText(activity);
input.setInputType(args.getInt(INPUT_TYPE));
input.setId(R.id.dialog_edit_text);
input.addTextChangedListener(this);
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setCancelable(args.getBoolean(CANCELABLE)).setTitle(args.getInt(TITLE)).setMessage(args.getString(MESSAGE)).setView(input).setPositiveButton(args.getInt(POSITIVE_TEXT), this);
int negativeText = args.getInt(NEGATIVE_TEXT);
if (negativeText != 0)
alert.setNegativeButton(negativeText, this);
AlertDialog dialog = alert.create();
dialog.setOnShowListener(this);
return dialog;
@Override
public void onShow(DialogInterface dialog)
// After device rotation there may be some text present.
if (((EditText)((AlertDialog) dialog).findViewById(R.id.dialog_edit_text)).length() == 0)
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
@Override
public void onClick(DialogInterface dialog, int which)
String text = ((EditText)((AlertDialog) dialog).findViewById(R.id.dialog_edit_text)).getText().toString();
((Callbacks) getActivity()).onTextViewDialogResult(which, getArguments().getInt(IDENTIFIER), text);
@Override
public void onCancel(DialogInterface dialog)
((Callbacks) getActivity()).onTextViewDialogActivityCancelled(getArguments().getInt(IDENTIFIER));
super.onCancel(dialog);
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
@Override
public void afterTextChanged(Editable s)
((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(s.length() > 0);
void setMessage(String message)
Bundle args = getArguments();
args.putString(MESSAGE, message);
setArguments(args);
interface Callbacks
void onTextViewDialogResult(int which, int identity, String text);
void onTextViewDialogActivityCancelled(int identity);
为您的活动添加工具(任何类型的活动都可以):
public class Myctivity extends AppCompatActivity implements TextViewDialogFragment.Callbacks
...
在您的活动中创建 diaglogFragment,如下所示:
final static int SOMETHING = 1;
myDF = TextViewDialogFragment.newInstance(R.string.my_title, "my message", SOMETHING, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, /* Whatever is best for your user. */ R.string.yay, android.R.string.cancel, true);
像这样处理您的活动中的结果:
@Override
public void onTextViewDialogResult(int which, int identity, String text)
if (which == AlertDialog.BUTTON_NEGATIVE)
// User did not want to do anything.
return;
// text now holds the users answer.
// Identity can be used if you use the same fragment for more than one type of question.
@Override
public void onTextViewDialogActivityCancelled(int identity)
// This is invoked if you set cancelable to true and the user pressed the back button.
您需要创建资源标识符,因此将此资源添加到 res/values 下的某处
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="dialog_edit_text" type="id"/>
</resources>
【讨论】:
【参考方案6】:这里是启用和禁用对话框正按钮的完整代码:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater layoutInflater = MainActivity.this.getLayoutInflater();
View view = layoutInflater.inflate(R.layout.dialog,null);
builder.setView(view);
builder.setTitle("Test");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialog, int which)
Toast.makeText(MainActivity.this, "Ok clicked", Toast.LENGTH_SHORT).show();
dialog.dismiss();
);
builder.setNegativeButton("cancel", null);
final AlertDialog alertDialog = builder.create();
alertDialog.show();
EditText editText = (EditText)view.findViewById(R.id.mobile_number);
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
editText.addTextChangedListener(new TextWatcher()
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
@Override
public void afterTextChanged(Editable s)
if (s.length() >= 1)
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
else
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
);
【讨论】:
【参考方案7】:您可以为编辑文本框编写一个监听器,并尝试启用或禁用按钮。这是 xamarin 的示例代码。
var dialog = builder.Create();
dialog.Show();
var btnOk = dialog.GetButton((int)DialogButtonType.Positive).Enabled = false;
_enterTextDialogEditText.AfterTextChanged += (sender, e) =>
if (!string.IsNullOrEmpty(_enterTextDialogEditText.Text))
dialog.GetButton((int)DialogButtonType.Positive).Enabled = true;
else
dialog.GetButton((int)DialogButtonType.Positive).Enabled = false;
;
【讨论】:
以上是关于如何禁用/启用对话框负正按钮?的主要内容,如果未能解决你的问题,请参考以下文章
如何禁用 Qt Mainwindow 快捷方式适用于无模式对话框