如何在Android中使一些AutoCompleteTextView建议项无法选择

时间:2017-05-24 19:49:25

标签: android android-arrayadapter autocompletetextview

我正在开发一个项目,要求我开发一个自动完成输入建议框,问题是建议项目被分类,他们每个类别应该突出显示并且不可点击。 我已经为此目的实现了自定义ArrayAdapter,但无法弄清楚如何使类别无法点击 这是我的自定义数组适配器代码

public class CustomAutoCompleteAdapter extends ArrayAdapter<String> {
    private static final int TYPE_ITEM = 0;
    private static final int TYPE_CATEGORY = 1;
    private TreeSet<Integer> sectionHeader = new TreeSet<Integer>();
    private LayoutInflater mInflater;


    public CustomAutoCompleteAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<String> objects) {
        super(context, resource, objects);
        mInflater = LayoutInflater.from(context);
    }
    public int getItemViewType(int position) {
        return sectionHeader.contains(position) ? TYPE_CATEGORY : TYPE_ITEM;
    }

    public void addHeader(String item) {
        super.add(item);
        sectionHeader.add(this.getCount() - 1);
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView==null){
            int type = getItemViewType(position);
            holder = new ViewHolder();
            if(type == TYPE_ITEM){
                convertView = mInflater.inflate(R.layout.item_layout,null);
                holder.textView = (TextView) convertView.findViewById(R.id.text);
            }
            else{
                convertView = mInflater.inflate(R.layout.category_layout,null);
                holder.textView = (TextView) convertView.findViewById(R.id.category);
                convertView.setClickable(false);
            }
            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.textView.setText(this.getItem(position));

        return convertView;
    }
    private static class ViewHolder {
        public TextView textView;
    }

}

2 个答案:

答案 0 :(得分:1)

CustomAutoCompleteAdapter中,覆盖isEnabled()方法以停用视图类型TYPE_CATEGORY

CustomAutoCompleteAdapter中添加以下代码:

@Override
public boolean isEnabled(int position) 
{
    return ((getItemViewType(position) != TYPE_CATEGORY));
}

希望这会有所帮助〜

答案 1 :(得分:0)

尝试通过将convertview和textview设置为&#34; unfocusable()&#34;来尝试从视图中移除焦点。像这样:

convertView.setFocusable(false);
holder.textview.setFocusable(false);

希望它能够发挥作用!