我正在开展一个项目,我必须从SQLite3数据库访问数据,并在输入时向用户显示建议。我已经尝试使用AutoCompleteTextView,但它无法正常工作。 我正在研究这段代码:
ArrayList<String> sugestion = new ArrayList<String>();
public ViewGroup onCreateView (LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState )
{
myAutoComplete = (AutoCompleteTextView) group.findViewById(R.id.searchit);
searchDB = new searchAdapter(getActivity());
searchDB.getWritableDatabase();
myAutoComplete.addTextChangedListener(new TextWatcher(){
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
suggestion = searchDB.getSuggestion(s.toString());
Collections.sort(suggestion);
String[] item = new String[suggestion.size()];
item = suggestion.toArray(item);
for(String word : item)
System.out.println(word);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
searchAdapter = new ArrayAdapter<String>(getActivity() , android.R.layout.simple_dropdown_item_1line, item);
myAutoComplete.setAdapter(searchAdapter);
...
}
我已经通过打印检查了ArrayList
(来自数据库)和String[]
数组,它们已经排列了字符串。
我的xml布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id = "@+id/group"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<AutoCompleteTextView
android:id="@+id/searchit"
android:layout_marginTop="15dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Choose The Country" >
<requestFocus />
</AutoCompleteTextView>
.....
</RelativeLayout>
键入时不显示字符串建议的下拉列表。我也使用textview而不是android.R.layout.simple_dropdown_item_1line
尝试了我自己的布局。我在这里失踪了什么?任何帮助将不胜感激
答案 0 :(得分:2)
试试这个
myAutoComplete.showDropDown()
答案 1 :(得分:1)
试试这个......
您仅在onCreate()
中设置了适配器。但是,您仅在item
中的onTextChanged
内填充了TextWatcher
数组的值。所以,尝试设置填充adapter
数组的item
afetr。
myAutoComplete.addTextChangedListener(new TextWatcher(){
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
suggestion = searchDB.getSuggestion(s.toString());
Collections.sort(suggestion);
String[] item = new String[suggestion.size()];
item = suggestion.toArray(item);
for(String word : item)
System.out.println(word);
searchAdapter = new ArrayAdapter<String>(getActivity() , android.R.layout.simple_list_item_1, item);
myAutoComplete.setAdapter(searchAdapter);
myAutoComplete.setThreshold(1);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});