在AutoCompleteTextview中获取过滤的数组大小

时间:2017-06-13 09:25:05

标签: android arraylist filtering android-adapter autocompletetextview

我正在开发用户可以搜索数据的项目。为此,我实施了AutoCompleteTextView

 autoComplete.setAdapter(new ArrayAdapter<String>(CheckRiskActivity.this,
                                        R.layout.auto_text_row, druglist));
                                autoComplete.setThreshold(1);
//druglist is my arraylist

文本更改侦听器如下:

autoComplete.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            // here I want to get the size of filtered array list every time when the user adds any character.
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start,
                                      int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start,
                                  int before, int count) {
        }
    });

说明:如果我的初始数组大小为100,并且用户输入'a',那么我想获得已过滤数组的大小。

注意:我尝试了autoComplete.getAdapter().getCount();但是在添加一个字符后它会给出实际结果。

5 个答案:

答案 0 :(得分:4)

您无法在TextWatcher中获得正确的过滤项目计数,因为过滤通常需要比TextWatcher事件侦听器更长的时间。因此,autoComplete.getAdapter().getCount()中的afterTextChanged()不正确。我建议使用自定义侦听器,每次更改过滤项时都会调用该侦听器。

我将提供两种类似的方法:使用单独的类并仅使用1个类。

APPROACH 1 : 您的适配器应如下所示:

import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import java.util.ArrayList;
import java.util.List;

public class AutoCompleteAdapter extends ArrayAdapter
{
    private List<String>    tempItems;
    private List<String>    suggestions;
    private FilterListeners filterListeners;

    public AutoCompleteAdapter(Context context, int resource, List<String> items)
    {
        super(context, resource, 0, items);

        tempItems = new ArrayList<>(items);
        suggestions = new ArrayList<>();
    }

    public void setFilterListeners(FilterListeners filterFinishedListener)
    {
        filterListeners = filterFinishedListener;
    }

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

    Filter nameFilter = new Filter()
    {
        @Override
        protected FilterResults performFiltering(CharSequence constraint)
        {
            if (constraint != null)
            {
                suggestions.clear();
                for (String names : tempItems)
                {
                    if (names.toLowerCase().startsWith(constraint.toString().toLowerCase()))
                    {
                        suggestions.add(names);
                    }
                }
                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 (filterListeners != null && filterList!= null)
                filterListeners.filteringFinished(filterList.size());

            if (results != null && results.count > 0)
            {
                clear();
                for (String item : filterList)
                {
                    add(item);
                    notifyDataSetChanged();
                }
            }
        }
    };
}

用于在过滤完成时通知您的界面:

public interface FilterListeners
{
    void filteringFinished(int filteredItemsCount);
}

你可以使用它:

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.AutoCompleteTextView;

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

public class MainActivity extends Activity implements FilterListeners
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        AutoCompleteTextView autoComplete = (AutoCompleteTextView) findViewById(R.id.autoComplete);
        autoComplete.setThreshold(1);

        List<String> stringList = new ArrayList<>();
        stringList.add("Black");
        stringList.add("White");
        stringList.add("Yellow");
        stringList.add("Blue");
        stringList.add("Brown");


        final AutoCompleteAdapter adapter = new AutoCompleteAdapter(this, android.R.layout.simple_list_item_1, stringList);
        adapter.setFilterListeners(this);
        autoComplete.setAdapter(adapter);
    }

    @Override
    public void filteringFinished(int filteredItemsCount)
    {
        Log.i("LOG_TAG", " filteringFinished  count = " + filteredItemsCount);
    }
}

APPROACH 2

    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.ArrayAdapter;
    import android.widget.AutoCompleteTextView;
    import android.widget.Filter;
    import java.util.ArrayList;
    import java.util.List;

    public class MainActivity extends Activity
    {
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            final AutoCompleteTextView autoComplete = (AutoCompleteTextView) findViewById(R.id.autoComplete);
            autoComplete.setThreshold(1);

            final List<String> stringList = new ArrayList<>();
            stringList.add("Black");
            stringList.add("White");
            stringList.add("Yellow");
            stringList.add("Blue");
            stringList.add("Brown");

            final ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, stringList)
            {
                private List<String> tempItems   = stringList;
                private List<String> suggestions = new ArrayList<>();

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

                Filter nameFilter = new Filter()
                {
                    @Override
                    protected FilterResults performFiltering(CharSequence constraint)
                    {
                        if (constraint != null)
                        {
                            suggestions.clear();
                            for (String names : tempItems)
                            {
                                if (names.toLowerCase().startsWith(constraint.toString().toLowerCase()))
                                {
                                    suggestions.add(names);
                                }
                            }
                            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;
                    filteringFinished(filterList.size());

                    if (results != null && results.count > 0)
                    {
                        clear();
                        for (String item : filterList)
                        {
                            add(item);
                            notifyDataSetChanged();
                        }
                    }
                }
            };
        };

        autoComplete.setAdapter(arrayAdapter);
    }

    private void filteringFinished(int filteredItemsCount)
    {
        Log.i("LOG_TAG", " filteringFinished  count = " + filteredItemsCount);
    }
}
当您在自动完成输入字段中输入内容并进行过滤时,将调用

filteringFinished()方法。

更新(Trie Search):

我创建了一个Github项目,其中有一个使用Trie搜索算法来提高自动完成性能的简单示例。

https://github.com/saqada/android-AutoCompleteWithTrie

答案 1 :(得分:1)

基本上,我们必须在Adapter类

实现Filterable
public class DrugListAdapter extends BaseAdapter implements
    Filterable {
Context context;
LayoutInflater inflater;
drugsFilter drugsFilter;

List<Drug> drugList = new ArrayList<>();
private List<Drug> drugListOrig;

public DrugListAdapter(Context context,
        List<Drug> drugList) {
    super();

    this.context = context;
    this.drugList = drugList;
    this.drugListOrig = new ArrayList<>(
            drugList);
    inflater = LayoutInflater.from(context);
}

public void resetData() {
    drugList = drugListOrig;
}



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

@Override
public Drug getItem(int position) {
    return drugList.get(position);
}

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

private class ViewHolder {
    TextView mVendorName;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = convertView;
    ViewHolder viewHolder;
    Drug item = drugList.get(position);
    if (view == null) {
        viewHolder = new ViewHolder();
        view = inflater.inflate(R.layout.item_drug,
                parent, false);
        viewHolder.mVendorName = (TextView) view
                .findViewById(R.id.item_drug_drug_name);
        view.setTag(viewHolder);
    } else {
        viewHolder = (ViewHolder) view.getTag();

    }
    viewHolder.mVendorName.setText(item.getDrug_name());
    return view;
}

@Override
public Filter getFilter() {
    if (drugsFilter == null) {
        drugsFilter = new DrugsFilter();
    }
    return drugsFilter;
}

public class DrugsFilter extends Filter {

    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults results = new FilterResults();
        // We implement here the filter logic
        if (constraint == null || constraint.length() == 0) {
            // No filter implemented we return all the list
            results.values = drugListOrig;
            results.count = drugListOrig.size();
        } else {
            // We perform filtering operation
            List<Drug> sList = new ArrayList<>();
            for (Drug p : drugList) {
                if (p.getDrug_name().toUpperCase()
                        .startsWith(constraint.toString().toUpperCase()))
                    sList.add(p);
            }

            results.values = sList;
            results.count = sList.size();

        }
        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint,
            FilterResults results) {
        if (results.count == 0)
            notifyDataSetInvalidated();
        else {
            drugList = (List<Drug>) results.values;
            notifyDataSetChanged();
        }

    }

}

}

此部分适用于EditTextTextWatcher

    String m;
    mDrugEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

            if (count < before) {
                adapter.resetData();
                adapter.notifyDataSetChanged();
            }
            adapter.getFilter().filter(s.toString());

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start,
                                      int before, int count) {
            if (s.length() == 0 || s.length() == 1) {
                mDrugEditText.invalidate();
            }
            if (s.length() == 3) {
                if (mDrugEditText
                        .isPerformingCompletion()) {
                    return;
                }
                adapter.resetData();
                adapter.notifyDataSetChanged();

            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            m = s.toString();
            adapter.getFilter().filter(s.toString());
        }
    });

答案 2 :(得分:0)

我假设您已经完成了android / java中可用的基本搜索选项,并且您对结果不满意。

如果您不想在每次文本更改时浏览整个列表,唯一的方法是实现执行此操作的数据结构。

明显的解决方案是trie。read this to get an idea about trie

现在,这适用于在搜索之前预处理数据的概念。由于你有有限的元素 - 它不会花费太多时间,你可以在页面加载时这样做。

步骤 - - 处理并索引所有加载元素。将索引放在k-ary树上(它将是32-ary,每个字符将是一个字母表)。 - 关于文本更改 - 遍历到节点并获取计数。需要O(1)。

我相信这是你能走的最快。

如果您有单词索引或者您只需要以startwith开头,上述内容将最有效。

答案 3 :(得分:0)

萨卡达的回答是一个非常好的方法,但是,我的下面答案给了我更好的表现。

autoCompleteTextViewCheckRisk.setAdapter(new ArrayAdapter<String>
            (CheckRiskActivity.this, R.layout.auto_text_row, druglist));
//druglist is the Arraylist of String.
autoCompleteTextViewCheckRisk.setThreshold(1);

文本更改侦听器:

autoCompleteTextViewCheckRisk.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {
            filter(druglist, s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start,
                                      int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start,
                                  int before, int count) {

        }
    });

过滤方法:

private void filter(ArrayList<String> originalArrayList, String query) {

    query = query.toLowerCase();
    filteredArrayList.clear();
    //filtered arraylist is also Arraylist of String, Just declared as global
    for (String itemName : originalArrayList) {
        final String text = itemName.toLowerCase();
        if (text.startsWith(query)) {
            filteredArrayList.add(itemName);
        }
    }

    if (filteredArrayList.size() == 0) {
        Log.i(TAG, "filter: No data found");
    }
}

答案 4 :(得分:0)

根据Ayaz Alifov的回答,您无法在TextWatcher中获得正确的过滤项计数,因为过滤通常比TextWatcher事件侦听器花费更长的时间。

但是我用timerTask做过一个花招。因此TextWatcher将在计数后执行。

editText.addTextChangedListener(
new TextWatcher() {
    @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
    @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

    private Timer timer=new Timer();
    private final long DELAY = 1000; // milliseconds

    @Override
    public void afterTextChanged(final Editable s) {
        timer.cancel();
        timer = new Timer();
        timer.schedule(
            new TimerTask() {
                @Override
                public void run() {
                      // adapter.getCount()  will give you the correct item's counts 
                      Log.d(TAG, "run: afterTextChanged " + adapter.getCount());
                }
            }, 
            DELAY
        );
    }
}
);

编辑日期:2019年9月5日

您还可以通过设置registerDataSetObserver来获得商品计数。

adapter.registerDataSetObserver(new DataSetObserver() {
    @Override
    public void onChanged() {
        super.onChanged();
        Log.d(TAG, "onChanged: " + adapter.getCount());
    }
});

这样,onChanged()将在每次文本更改时调用。但是,如果建议列表为空,则不会被调用。