搜索ListView不起作用 - 为什么?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了搜索ListView不起作用 - 为什么?相关的知识,希望对你有一定的参考价值。

嗨,我在Dialog中有一个listView,我已经为Dialog设置了一个自定义适配器。

我查找并设置addTextChangedListener,但似乎不起作用。

我只想搜索列表并在用户键入编辑文本时刷新列表

不知道我在哪里弄错了

这是我的代码

private void showCompaniesDialog(List<Company> companies) {
    if(companies != null) {
        final Dialog dialog = new Dialog(getContext());
        // dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.dialog_company_listview);

        Button btndialog = (Button) dialog.findViewById(R.id.btndialog);
        btndialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.dismiss();
            }
        });

        ListView listView = (ListView) dialog.findViewById(R.id.listview);
        //ArrayAdapter arrayAdapter = new ArrayAdapter(getContext(), R.layout.company_list_item, R.id.tv, companies);
        CompanyAdapter companyAdapter = new CompanyAdapter(getActivity(), 0, companies);
        listView.setAdapter(companyAdapter);

        //HERE I SET THE TEXT FILTER ENABLED
        listView.setTextFilterEnabled(true);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //textView.setText("You have clicked : " + companies[position]);
                dialog.dismiss();
            }
        });

        //HERE I ADD CHANGED LISTENER
        EditText etSearch = (EditText) dialog.findViewById(R.id.etSearch);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //companyAdapter.getFilter().filter(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {
                companyAdapter.getFilter().filter(editable);
            }
        });

        dialog.show();
    }

}

这是该公司的自定义适配器

public class CompanyAdapter extends ArrayAdapter<Company>{
    private Activity activity;
    private List<Company> lCompany;
    private LayoutInflater inflater = null;

    public CompanyAdapter (Activity activity, int textViewResourceId, List<Company> lCompany){
        super(activity, textViewResourceId, lCompany);
        try{
            this.activity = activity;
            this.lCompany = lCompany;

            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public int getCount(){
        return lCompany.size();
    }

    public Company getItem (Company position){
        return position;
    }

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

    public  class ViewHolder {
        public TextView display_name;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        final ViewHolder holder;
        try {
            if (convertView == null) {
                vi = inflater.inflate(R.layout.company_list_item, null);
                holder = new ViewHolder();

                holder.display_name = (TextView) vi.findViewById(R.id.tvCompanyName);


                vi.setTag(holder);
            } else {
                holder = (ViewHolder) vi.getTag();
            }
            holder.display_name.setText(lCompany.get(position).getName());

        } catch (Exception e) {
            e.printStackTrace();

        }
        return vi;
    }
}

任何建议都会非常有帮助

答案

您需要将Filterable接口添加到您的适配器。

您可以将以下代码添加到适配器

public Filter getFilter() {
    return new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            String filterString = constraint.toString().toLowerCase();

            FilterResults results = new FilterResults();

            final List < String > list = originalData;

            int count = list.size();
            final ArrayList < String > nlist = new ArrayList < String > (count);

            String filterableString;

            for (int i = 0; i < count; i++) {
                filterableString = list.get(i);
                if (filterableString.toLowerCase().contains(filterString)) {
                    nlist.add(filterableString);
                }
            }

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

            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            filteredData = (ArrayList < String > ) results.values;
            notifyDataSetChanged();
        }
    }
}

您需要根据您的要求进行更改

另一答案

我使用与ListView配对的SearchView实现此功能。 SearchView有一些内置方法,可以在更改文本或单击“搜索”时触发,您可以覆盖这些方法以在ListView中设置过滤器。

my activity.Java

        // Setup the ListView
        // breedListView = (ListView)rootView.findViewById(R.id.breedListView);

        // My 'Activity' is actually a ListFragment so getListView() is how it is done
        breedListView = getListView();
        breedListView.setFastScrollEnabled(true);
        breedListView.setTextFilterEnabled(true);

        // Setup the searchView
        searchView = (SearchView)rootView.findViewById(R.id.searchView);                    
        setupSearchView();

        // Set some default properties
        private void setupSearchView() {
            searchView.setIconifiedByDefault(false);
            searchView.setOnQueryTextListener(this);
            searchView.setSubmitButtonEnabled(false);
            searchView.setQueryHint("Search");
        }

        // Reset the filter as the user types
        public boolean onQueryTextChange(String newText) {
            if (TextUtils.isEmpty(newText)) {
                breedListView.clearTextFilter();
            } else {
                breedListView.setFilterText(newText.toString());
            }
            return true;
        }

        // Reset the filter when Search is pressed
        public boolean onQueryTextSubmit(String query) {
            if (TextUtils.isEmpty(query)) {
                breedListView.clearTextFilter();
            } else {
                breedListView.setFilterText(query.toString());
            }
            return false;
        }


        // After getting/refreshing the list, do this to reapply the query to the new list
        CharSequence suggestWord = searchView.getQuery();
        searchView.setQuery(suggestWord, true);

MyActivity.xml

        <?xml version="1.0" encoding="utf-8"?>
        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <SearchView
                android:id="@+id/searchView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" >
            </SearchView>

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="match_parent">     
                    <ListView
                      android:id="@android:id/list"
                      android:layout_weight="0.1"
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content" >
                    </ListView>

                    <ListView
                        android:id="@+id/listIndex"
                        android:dividerHeight="0dp"
                        android:divider="@null"
                        android:scrollbars="none"
                        android:layout_width="30dp"
                        android:layout_height="wrap_content" >
                    </ListView>
            </LinearLayout> 
        </LinearLayout>

以上是关于搜索ListView不起作用 - 为什么?的主要内容,如果未能解决你的问题,请参考以下文章

搜索ListView不起作用 - 为什么?

片段中 ListView 的自定义适配器不起作用

Onclicklistener 在片段列表视图中不起作用

listview onclick toast在片段中不起作用[重复]

在内部片段类中使用ListView

搜索在 ArrayAdapter 和 ListView 中不起作用