我对Android 2.2上的AutocompleteView的建议项有一个奇怪的问题。我正在使用自定义ArrayAdapter和Filter类实现。
当我输入AutocompleteView时,输入两个字符后弹出建议下拉列表,如下面的屏幕截图所示:
当我输入第三个字符时,下拉列表消失:
输入第四个字符后,会再次显示建议下拉列表:
我不明白为什么输入的字符数量不均匀时下拉列表会消失。
调试时我注意到,当输入偶数字符时,会调用getView()两次,但是对于不均匀的数量,会调用一次。这可能是造成错误行为的原因吗?
这是我的源代码:
public class AutoCompleteActivity extends Activity {
protected AutoCompleteTextView autoCompleteView;
protected AutoCompleteAdapter suggsAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomp);
autoCompleteView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
autoCompleteView.setAdapter(new AutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line, new String[1]));
}
private class AutoCompleteAdapter extends ArrayAdapter implements Filterable {
protected LayoutInflater mInflater;
protected Filter filter;
public AutoCompleteAdapter(Context context, int textViewResourceId, String[] items) {
super(context, textViewResourceId, items);
filter = new SuggestionsFilter();
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = mInflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
}
TextView tt = (TextView) v.findViewById(android.R.id.text1);
tt.setText("Suggestion item");
return v;
}
public Filter getFilter() {
return filter;
}
private class SuggestionsFilter extends Filter {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
return null;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
notifyDataSetChanged();
}
}
}
}
...和我的布局文件:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- Pretty hint text, and maxLines -->
<AutoCompleteTextView android:id="@+id/autocomplete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:maxLines="1"
android:imeOptions="actionSearch"
android:layout_toLeftOf="@+id/spinner" />
答案 0 :(得分:6)
我找到了解决问题的方法。我没有在results.count
方法中设置performFiltering
。将此属性设置为例如results.count = 1
通过消失的建议项目解决了这个问题。