【发布时间】:2017-07-20 06:14:57
【问题描述】:
我正在开发一个为 AlertDialog 使用自定义视图的应用程序。我想让它在编辑文本字段为空时禁用提交按钮。我在网上找到了一些示例,但在我的实现中,对提交按钮的引用一直返回 null。一旦我在edittext中输入任何文本,应用程序就会崩溃。这是 alertdialog 类,我尝试抓取按钮的失败已被注释掉:
public class FileNameDialogFragment extends DialogFragment {
private static final String TAG = "dialogFragment";
private EditText namefield;
private Button submit;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
LayoutInflater inflater = LayoutInflater.from(getActivity());
View v = inflater.inflate(R.layout.file_prompt_dialog, null, false);
namefield = (EditText) v.findViewById(R.id.nameField);
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle(R.string.dialog_title)
.setView(v)
.setIcon(R.drawable.icon)
.setPositiveButton(R.string.btnOK, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
MainActivity.setFileName(namefield.getText().toString());
String fileName = namefield.getText().toString();
Toast.makeText(getActivity(), MainActivity.getUrl().toString(), Toast.LENGTH_SHORT).show();
MainActivity.download(MainActivity.getUrl(), getActivity(), MainActivity.getPath(), fileName);
}
})
.setNegativeButton(R.string.btnCancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismiss();
}
})
.create();
//I have also tried to place the code that is below here. neither works
dialog.show();
/*
* this is the section of code that i am having trouble with
*
submit = ((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE);
namefield.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//left intentionally blank
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count == 0){
submit.setEnabled(false);
}else{
submit.setEnabled(true);<--NullPointerException
}
}
@Override
public void afterTextChanged(Editable s) {
//left intentionally blank
}
});*/
return dialog;
}
}
我希望了解如何使这项工作成为验证输入的一种方式。我不希望用户能够将此字段留空,因为输入用于命名从 Internet 下载的文件。
【问题讨论】:
-
您在对话框中设置自定义视图。我认为标准的
getButton行不通,你需要使用v.findViewByID() -
请附上日志。
标签: android android-alertdialog addtextchangedlistener