AutoCompleteTextView:不输入内容completionThreshold = 0,任意检索自定义匹配规则

AutoCompleteTextView:继承自EditText,是可提供建议用以自动补全文本的输入框,其基本用法相信大家都很了解,本文记录一下使用过程中遇到的一些问题:

  • completionThreshold最小值为1,那么如果我想不输入任何内容也可以弹出提示列表怎么办?

查看AutoCompleteTextView源码,我们会发现当completionThreshold<=0时,会默认修改为1:

    /**
     * <p>Specifies the minimum number of characters the user has to type in the
     * edit box before the drop down list is shown.</p>
     *
     * <p>When <code>threshold</code> is less than or equals 0, a threshold of
     * 1 is applied.</p>
     *
     * @param threshold the number of characters to type before the drop down
     *                  is shown
     *
     * @see #getThreshold()
     *
     * @attr ref android.R.styleable#AutoCompleteTextView_completionThreshold
     */
    public void setThreshold(int threshold) {
        if (threshold <= 0) {
            threshold = 1;
        }

        mThreshold = threshold;
    }

那么我们如果想让completionThreshold为0,在不输入任何内容时也有提示信息该怎么办呢?

继续查看源码,会发现enoughToFilter()方法:

     /**
     * Returns <code>true</code> if the amount of text in the field meets
     * or exceeds the {@link #getThreshold} requirement.  You can override
     * this to impose a different standard for when filtering will be
     * triggered.
     */
    public boolean enoughToFilter() {
        if (DEBUG) Log.v(TAG, "Enough to filter: len=" + getText().length()
                + " threshold=" + mThreshold);
        return getText().length() >= mThreshold;
    }

其作用就是用以判断输入长度是否满足显示提示列表,那么我们只需要自定义AutoCompleteTextView重写该方法即可:

public class MyAutoCompleteTextView extends AutoCompleteTextView {
    public MyAutoCompleteTextView(Context context) {
        super(context);
    }

    public MyAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    @Override
    public boolean enoughToFilter() {
        return true;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        //当控件获得焦点显示提示列表
        performFiltering(getText(), KeyEvent.KEYCODE_UNKNOWN);
    }

}

点击空白区域以后,提示列表消失,想再显示出来怎么办?

在onClick()方法中调用showDropDown()即可:


myAutoCompleteTextView.setOnClickListener(v -> myAutoCompleteTextView.showDropDown());

  • ArrayAdapter只能筛选以输入内容开头的信息,不能满足我们的需求,如:我们想筛选任意位置?

查看ArrayAdapter源码,其继承自继承自BaseAdapter并实现了Filterable接口,通过ArrayFilter的performFiltering完成筛选:

那么我们只需要自定义Adapter,使用自己的Filter:

public class CustomAdapter<T> extends BaseAdapter implements Filterable {

    private Context mContext;
    private List<String> mObjects;
    private ArrayList<String> mOriginalValues;
    private final Object mLock = new Object();
    private CustomFilter mFilter;

    public CustomAdapter(Context context) {
        this.mContext = context;
        mFilter = new CustomFilter();
    }

    public void transforData(List<String> items) {
        this.mObjects = items;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return mObjects.size();
    }

    @Override
    public String getItem(int position) {
        return mObjects.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.simple_dropdown_item_1line, null);
            viewHolder.content = convertView.findViewById(R.id.text1);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.content.setText(mObjects.get(position));
        return convertView;
    }

    class ViewHolder {
        TextView content;
    }

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

    private class CustomFilter extends Filter {
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results = new FilterResults();
            if (mOriginalValues == null) {
                synchronized (mLock) {
                    mOriginalValues = new ArrayList<>(mObjects);
                }
            }
            int count = mOriginalValues.size();
            ArrayList<String> values = new ArrayList<>();
            for (int i = 0; i < count; i++) {
                String value = mOriginalValues.get(i);
                if (null != value && null != constraint
                        && value.toLowerCase().contains(constraint.toString().toLowerCase())) {
                    values.add(value);
                }
            }
            results.values = values;
            results.count = values.size();
            return results;
        }
        @Override
        protected void publishResults(CharSequence arg0, FilterResults results) {
            mObjects = (List<String>) results.values;
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}


根据需求修改performFiltering方法即可

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值