如何基于字符串长度控制MultiAutoCompleteTextView的提示功能
基于整体字符串长度触发MultiAutoCompleteTextView的提示
看起来你已经摸透了默认threshold的逻辑——它是针对每个分词后的独立项判断是否触发提示的,所以调整阈值后,触发时机才会跟着分词位置变化。如果想要改成基于整个输入字符串的总长度来触发提示,我们可以通过自定义MultiAutoCompleteTextView来实现。
核心思路
默认的MultiAutoCompleteTextView靠enoughToFilter()方法判断是否显示提示,这个方法默认会检查光标所在分词项的长度是否达标。我们只需要重写这个方法,把判断逻辑改成检查整个文本的长度即可。
自定义控件实现
创建一个继承自MultiAutoCompleteTextView的自定义类,重写enoughToFilter():
public class LengthTriggerMultiAutoCompleteTextView extends MultiAutoCompleteTextView { public LengthTriggerMultiAutoCompleteTextView(Context context) { super(context); } public LengthTriggerMultiAutoCompleteTextView(Context context, AttributeSet attrs) { super(context, attrs); } public LengthTriggerMultiAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected boolean enoughToFilter() { // 判断整个输入文本的长度是否达到设置的阈值 return getText().length() >= getThreshold(); } }
使用方式
- 在布局文件里替换原来的
MultiAutoCompleteTextView为这个自定义控件:
<com.your.package.name.LengthTriggerMultiAutoCompleteTextView android:id="@+id/custom_multi_auto_complete" android:layout_width="match_parent" android:layout_height="wrap_content" android:threshold="2" /> <!-- 这里的阈值就是整个字符串的触发长度 -->
- 继续保留你原来的空格分词器设置,比如:
LengthTriggerMultiAutoCompleteTextView autoComplete = findViewById(R.id.custom_multi_auto_complete); // 自定义空格分词器 autoComplete.setTokenizer(new MultiAutoCompleteTextView.Tokenizer() { @Override public int findTokenStart(CharSequence text, int cursor) { int i = cursor; while (i > 0 && text.charAt(i - 1) != ' ') { i--; } while (i < cursor && text.charAt(i) == ' ') { i++; } return i; } @Override public int findTokenEnd(CharSequence text, int cursor) { int i = cursor; int len = text.length(); while (i < len) { if (text.charAt(i) == ' ') { return i; } else { i++; } } return len; } @Override public CharSequence terminateToken(CharSequence text) { int i = text.length(); while (i > 0 && text.charAt(i - 1) == ' ') { i--; } return (i > 0 && text.charAt(i - 1) == ' ') ? text : text + " "; } }); // 设置你的提示适配器 autoComplete.setAdapter(yourSuggestionAdapter);
效果说明
现在当你输入的整个字符串长度达到设置的threshold值时,就会触发提示,不再受分词项长度的限制。比如阈值设为2,只要输入了2个字符(不管是不是在同一个分词项里),就会弹出预测结果。
内容的提问来源于stack exchange,提问作者user3892282
相关产品推荐
相关产品推荐

