如何解决结合 AlertDialog 和 AutoCompleteText
所以我想要做的是有一个 AlertDialog,用户可以在其中将自己的杂货添加到数据库中。我希望程序在用户打字时给出建议。我想将 AlertDialog 与 AutoCompleteTextView 结合起来。我在自动完成部分 https://developer.android.com/reference/android/widget/AutoCompleteTextView.html 中遵循了本指南,但我似乎做对了。
主要内容:
public void add(View caller) {
MaterialAlertDialogBuilder mBuilder = new MaterialAlertDialogBuilder(mainActivity.this);
mBuilder.setTitle(R.string.dialog_title);
mBuilder.setView(R.layout.add_items_dialog);
mBuilder.setMessage("Enter a grocery");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,GROCERIES);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.name_text_field);
textView.setAdapter(adapter);
mBuilder.setPositiveButton("Add",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface,int which) {
}
});
mBuilder.setNegativeButton(R.string.dismiss_label,int i) {
dialogInterface.dismiss();
}
});
AlertDialog mDialog = mBuilder.create();
mDialog.show();
add_items_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/name_text_field"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/dp_16"
android:layout_marginEnd="@dimen/dp_16"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:hint="@string/enter_text"
android:textColorHint="@color/colorDarkGreen"
style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/et_input"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="text"
android:singleLine="true" />
</com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
第 textView.setAdapter(adapter)
行出错:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AutoCompleteTextView.setAdapter(android.widget.ListAdapter)' 在一个空对象引用上
我想这与将适配器设置为错误的文本视图有关,但也可能完全不同。有什么建议吗?
解决方法
您需要更改 mbuilder.addView(R.layout.add_itemes_dialog)
通过
View view =LayoutInflater.from(this).inflate(R.layout.add_itemes_dialog,null);
builder.setView(view);
// and to find your AutoCompleteTextView
AutoCompleteTextView textView = (AutoCompleteTextView) view.findViewById(R.id.et_input);
也在您的 xml 文件中通过 MaterialAutoCompleteTextView 更改 TextInputEditText,它应该可以工作
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。