我正在使用autocompleteTextview尝试从服务器获取一些数据。
private void initAutoCompleteTextViews() {
mAutoCompleteList = new ArrayList<String>();
mStreet.setThreshold(3);
mStreet.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 3){
getSuggestion();
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
我的问题是当我再次选择一个建议和getSuggestion()时,因为长度也大于3.
是否有任何解决方案我可以选择建议并将其设置为autocompleteTextview?
答案 0 :(得分:2)
我认为它可以帮到你
private AutoCompleteTextView mSearchbar;
private ArrayAdapter<String> mAutoCompleteAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
mAutoCompleteAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line);
mSearchbar = (AutoCompleteTextView) findViewById(R.id.searchbar);
mSearchbar.setThreshold(3);
mSearchbar.setAdapter(mAutoCompleteAdapter);
mSearchbar.addTextChangedListener(new TextWatcher() {
private boolean shouldAutoComplete = true;
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
shouldAutoComplete = true;
for (int position = 0; position < mAutoCompleteAdapter.getCount(); position++) {
if (mAutoCompleteAdapter.getItem(position).equalsIgnoreCase(s.toString())) {
shouldAutoComplete = false;
break;
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (shouldAutoComplete) {
new DoAutoCompleteSearch().execute(s.toString());
}
}
}
}
private class DoAutoCompleteSearch extends AsyncTask<String, Void, ArrayList<String>> {
@Override
protected ArrayList<String> doInBackground(String... params) {
ArrayList<String> autoComplete = new ArrayList<String>();
//do autocomplete search and stuff.
return autoComplete;
}
@Override
protected void onPostExecute(ArrayList<String> result) {
mAutoCompleteAdapter.clear();
for (String s : result)
mAutoCompleteAdapter.add(s);
}
}
答案 1 :(得分:0)
实施
mStreet.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(mContext,"new item selected.", Toast.LENGTH_LONG).show();
// your code when item is selected from suggestion
}
});
而不是实施addTextChangedListene(new TextWatcher)
。
答案 2 :(得分:0)
在你的添加textChanged Listener中,在if循环中添加额外条件
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 3 && mStreet.getText().length() != ResultString.length()){
getSuggestion();
}
在你的getSuggestion()方法中使用像这样的字符串,
public void getSuggestion(){
.......
......
ResultString = (Your Server Response);
}
答案 3 :(得分:0)
有一个方法isSelected()。尝试使用它。
与actv.isSelected();
类似