gpt4 book ai didi

java - 如何显示自动完成 TextView 的建议列表,该列表仅显示以输入字符开头的单词

转载 作者:行者123 更新时间:2023-12-01 09:05:49 25 4
gpt4 key购买 nike

我想显示仅包含以输入字符开头的单词的建议列表,而不是包含输入字符的单词。

例如,假设我输入 L ,它会显示类似的列表

["Launga Beach","Launga Hills","Launga Woods"] 

不是这样

["Echo Lake,"Fields Landing","Green Vally Lake"]

这是我的代码

 ArrayAdapter<String> cityAdapter = new ArrayAdapter<String>(getActivity(),R.layout.auto_complete_select_dialog_item,mCityZipCodeMasterForCity.getCity());
cityAutoCompleteTextView.setThreshold(1);
cityAutoCompleteTextView.setAdapter(cityAdapter);
cityAutoCompleteTextView.setOnFocusChangeListener(new AutoCompleteTextValidator());

有没有办法在android中的自动完成 TextView 中实现这一点?

谢谢!

最佳答案

下面我添加了示例Adapter供您使用Custom过滤器引用。

您只需要过滤逻辑。

自定义适配器.java

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;

import java.util.ArrayList;
import java.util.List;


public class CustomAdapter extends ArrayAdapter<String> {

Context context;
int resource, textViewResourceId;
List<String> items, tempItems, suggestions;

public CustomAdapter(Context context, int resource, int textViewResourceId, List<String> items) {
super(context, resource, textViewResourceId, items);
this.context = context;
this.resource = resource;
this.textViewResourceId = textViewResourceId;
this.items = items;
tempItems = new ArrayList<String>(items); // this makes the difference.
suggestions = new ArrayList<String>();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
// Handle your layout here
return view;
}

@Override
public Filter getFilter() {
return nameFilter;
}

/**
* Custom Filter implementation for custom suggestions we provide.
*/
Filter nameFilter = new Filter() {
@Override
public CharSequence convertResultToString(Object resultValue) {
return resultValue.toString();
}

@Override
protected FilterResults performFiltering(CharSequence constraint) {
if (constraint != null) {
suggestions.clear();

// Here you can add your pattern like L* for starting string with 'L'
for (String item : tempItems) {
if (item.startsWith("your pattern here")) {
suggestions.add(item);
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}

@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
List<String> filterList = (ArrayList<String>) results.values;
if (results != null && results.count > 0) {
clear();
for (String item : filterList) {
add(item);
notifyDataSetChanged();
}
}
}
};
}

谢谢。

关于java - 如何显示自动完成 TextView 的建议列表,该列表仅显示以输入字符开头的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41295375/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com