使用过滤器进行列表视图搜索

时间:2015-04-09 15:03:10

标签: android listview

我正在尝试使用过滤器进行列表视图搜索,但是我收到错误“FilterResults无法解析为类型”,如果我添加 “import android.widget.Filter; import android.widget.Filter.FilterResults;“在开头,出现另一个错误”类型android.widget.Filter.FilterResults不可见“,真的不知道如何修复。 这是我的食谱适应器:

     class RecipesAdapter extends ArrayAdapter<Recipe> implements Filterable{


         LayoutInflater inflater;
         ArrayList<Recipe> arraylist;

     public RecipesAdapter(Context context, ArrayList<Recipe> arraylist) {
            super(context, R.layout.row_recipe, recipes);
            this.arraylist = arraylist;
            inflater = LayoutInflater.from(context);
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if(itemView == null) {
                itemView = inflater.inflate(R.layout.row_recipe, parent, false);
            }

            final Recipe currentEvent = recipes.get(position);

            TextView recipeName = (TextView) itemView.findViewById(R.id.recipename);
            recipeName.setText(currentEvent.name);

            TextView time = (TextView) itemView.findViewById(R.id.timeContent);
            time.setText(currentEvent.created_at);


            return itemView;
        }

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

 @Override
 public Filter getFilter() {
     Filter filter = new Filter() {

         @SuppressWarnings("unchecked")
         @Override
         protected void publishResults(CharSequence constraint,FilterResults results) {

             recipes = (ArrayList<Recipe>) results.values; // has the filtered values
             notifyDataSetChanged();  // notifies the data with new filtered values
         }

         private void notifyDataSetChanged() {
            // TODO Auto-generated method stub

        }

        @Override
         protected FilterResults performFiltering(CharSequence constraint) {
             FilterResults results = new FilterResults();        // Holds the results of a filtering operation in values
             ArrayList<Recipe> FilteredArrList = new ArrayList<Recipe>();

             if (recipes == null) {
                 recipes = new ArrayList<Recipe>(); // saves the original data in mOriginalValues
             }

             /********
              * 
              *  If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
              *  else does the Filtering and returns FilteredArrList(Filtered)  
              *
              ********/
             if (constraint == null || constraint.length() == 0) {

                 // set the Original result to return  
                 results.count = recipes.size();
                 results.values = recipes;
             } else {
                 constraint = constraint.toString().toLowerCase();
                 for (int i = 0; i < recipes.size(); i++) {
                     Recipe data = recipes.get(i);
                     if (data.toLowerCase().startsWith(constraint.toString())) {
                         FilteredArrList.add(data);
                     }
                 }
                 // set the Filtered result to return
                 results.count = FilteredArrList.size();
                 results.values = FilteredArrList;
             }
             return results;
         }

        @Override
        public boolean onLoadClass(Class clazz) {
            // TODO Auto-generated method stub
            return false;
        }
     };
     return filter;
 }

已经在Recipesadapter中声明了ArrayList配方。

1 个答案:

答案 0 :(得分:0)

我是在不使用任何额外点击的情况下以非常简单的方式手动完成的,只需键入编辑文本,结果就在列表视图中。列表视图元素根据编辑文本中键入/删除的字符进行更改:

MainActivity.java

package com.example.examplesearch;

import java.util.ArrayList;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends ActionBarActivity {
    ArrayAdapter<String> adapter1 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView list1 = (ListView) findViewById(R.id.list1);
        final EditText search = (EditText) findViewById(R.id.search);
        final ArrayList<String> arraylist = new ArrayList<String>();
        arraylist.add("Balvier");
        arraylist.add("Sudhier");
        arraylist.add("Abhinay");
        arraylist.add("Amit");
        arraylist.add("Dilip");
        final ArrayList<String> newArraylist = new ArrayList<String>();
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getApplicationContext(),
                android.R.layout.simple_dropdown_item_1line, arraylist);

        newArraylist.clear();

        list1.setAdapter(adapter);
        search.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                // TODO Auto-generated method stub
                newArraylist.clear();
                for (int i = 0; i < arraylist.size(); i++) {
                    if (search.getText().length() <= arraylist.get(i).length()) {
                        if (search
                                .getText()
                                .toString()
                                .equalsIgnoreCase(
                                        (String) arraylist.get(i).subSequence(
                                                0, search.getText().length()))) {
                            newArraylist.add(arraylist.get(i).toString());
                        }
                    }
                }
                adapter1 = new ArrayAdapter<String>(getApplicationContext(),
                        android.R.layout.simple_dropdown_item_1line,
                        newArraylist);
                list1.setAdapter(adapter1);
            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

        });

    }
}

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.examplesearch.MainActivity" >

    <EditText
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="50dp" />

    <ListView
        android:id="@+id/list1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#000000" 
        android:layout_below="@+id/search"/>

</RelativeLayout>