【发布时间】:2017-03-23 09:50:26
【问题描述】:
我正在放入一个我在另一个项目中使用过的自动完成文本视图,代码被复制并在另一个项目上运行良好,但它现在不适合我。我的目标是在数据库中搜索类似的描述,并在相关的下拉列表中返回结果。每次输入字符时,我都会返回结果,但未显示下拉列表。 arraylist、adapter 和 autocompletetext 视图都在 create 方法中定义,而 text watcher 在同一个方法中定义。有什么想法吗?
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="60dp"
android:orientation="horizontal"
android:background="@drawable/border"
android:padding="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Description *:"
android:layout_gravity="center_vertical"
android:layout_marginRight="5dp"/>
<!--<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/txtDescription"/>-->
<AutoCompleteTextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/txtDescription"
android:textAppearance="@style/SmallText"
android:gravity="center_vertical"
android:inputType="textMultiLine"
android:layout_gravity="center_vertical"/>
</LinearLayout>
</LinearLayout>
ArrayList<String> descriptions = Shared.db.DB_Equipment.GetDescriptions("");
final ArrayAdapter<String> adapter = new ArrayAdapter<>(thisActivity, android.R.layout.simple_dropdown_item_1line, descriptions);
txtDescription = (AutoCompleteTextView)rootView.findViewById(R.id.txtDescription);
txtDescription.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(final CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.length() > 1) {
new AsyncTask<String, Void, ArrayList<String>>() {
@Override
protected ArrayList<String> doInBackground(String... params) {
ArrayList<String> descs = null;
try {
descs = Shared.db.DB_Equipment.GetDescriptions(charSequence.toString());
} catch (Exception e) {
e.printStackTrace();
}
return descs;
}
@Override
protected void onPostExecute(ArrayList<String> descriptions) {
adapter.clear();
if (descriptions != null)
for (String desc : descriptions) {
adapter.add(desc);
}
adapter.notifyDataSetChanged();
}
}.execute(charSequence.toString());
}
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
}
});
【问题讨论】:
-
把java代码也贴出来
-
见stackoverflow.com/a/19860624/2252830,只需从
runQuery()方法返回你的数据库Cursor,不需要TextWatcher,AsyncTask等等
标签: android autocompletetextview