Java 在android中的listview自定义适配器中使用筛选器类

Java 在android中的listview自定义适配器中使用筛选器类,java,android,Java,Android,我正在android中为listview使用自定义适配器。我在其中创建了一个过滤器类 public class filter_here extends Filter{ //ArrayList<String> Names=new ArrayList<String>(); ArrayList<String> store_names; @Override protected FilterResults

我正在android中为listview使用自定义适配器。我在其中创建了一个过滤器类

public class filter_here extends Filter{
        //ArrayList<String> Names=new ArrayList<String>(); 
        ArrayList<String> store_names;
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            // TODO Auto-generated method stub
             store_names=new ArrayList<String>();
            for(int i=0;i<store_list.size();i++)
            {
                store_names.add(store_list.get(i).store_name);
            }
            FilterResults Result = new FilterResults();
            // if constraint is empty return the original names
            if(constraint.length() == 0 ){
                Result.values = store_names;
                Result.count = store_names.size();
                return Result;
            }

            ArrayList<String> Filtered_Names = new ArrayList<String>();
            String filterString = constraint.toString().toLowerCase();
            String filterableString;

            for(int i = 0; i<store_list.size(); i++){
                filterableString = store_list.get(i).store_name;
                if(filterableString.toLowerCase().contains(filterString)){
                    Filtered_Names.add(filterableString);
                }
            }
            Result.values = Filtered_Names;
            Result.count = Filtered_Names.size();

            return Result;
        }

        @Override
        protected void publishResults(CharSequence constraint,FilterResults results) {
            // TODO Auto-generated method stub
            store_names = (ArrayList<String>) results.values;
            notifyDataSetChanged();
        }

    }
编辑:


仍然不起作用。

您是否为EditText实现了TextWatcher listenr?也发布日志文件以便更容易理解问题更改此行“store_names=ArrayList results.values;”“存储\u list=ArrayList results.values;”@bean\u droid store\u list是ArrayList,store\u names是ArrayList。我正在将store\u list这是store\u数据对象的ArrayList传递到适配器中。为什么不使用已经实现可过滤iface的现有适配器?
package com.igloo.adapters;

import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.androidquery.AQuery;
import com.igloo.adapters.CustomStoreAdapter.StoreHolder;
import com.igloo.classes.Store_data;

import com.igloo.storelocater.R;
import com.igloo.storelocater.StoreFinal;

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.DocumentsContract.Document;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class CustomDetailsAdapter extends BaseAdapter implements Filterable {
    private Activity context;
    private LayoutInflater details_inflate;
    ArrayList<Store_data> store_list;
    AQuery androidQuery;
    String URL_image="http://footballultimate.com/storelocator/resource/uploads/";
    double current_latitude,current_longitude;
    float[] result_arr;
    filter_here filter;
    public CustomDetailsAdapter(Activity context,ArrayList<Store_data> store_list,double current_latitude,double current_longitude)
    {
        this.context=context;
        details_inflate=LayoutInflater.from(context);
        this.store_list=store_list;
        this.current_latitude=current_latitude;
        this.current_longitude=current_longitude;
         filter = new filter_here();


    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return this.store_list.size();
    }

    @Override
    public Object getItem(int index) {
        // TODO Auto-generated method stub
        return store_list.get(index);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }



    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        DetailsHolder holder;
        if(convertView==null)
        {
            convertView = details_inflate.inflate(R.layout.list_store_names_single, null);
            holder=new DetailsHolder();
            holder.txt_store_specific_name = (TextView) convertView.findViewById(R.id.txt_store_names);
            holder.root_store_name_layout = (RelativeLayout) convertView.findViewById(R.id.root_store_names_layout);
            holder.store_name=(ImageView) convertView.findViewById(R.id.iv_store_name);
            holder.priority_star=(ImageView) convertView.findViewById(R.id.iv_star);
            holder.txt_distance=(TextView) convertView.findViewById(R.id.txt_store_distance);

            convertView.setTag(holder);
        }
        else
        {
            holder = (DetailsHolder) convertView.getTag();
        }
        androidQuery=new AQuery(context);
        holder.txt_store_specific_name.setText(store_list.get(position).store_name);
        holder.root_store_name_layout.setTag(store_list.get(position));
        androidQuery.id(holder.store_name).image(URL_image+store_list.get(position).store_image);
        //String parameter=""+distance(current_latitude,current_longitude,Double.parseDouble(store_list.get(position).store_latitude),Double.parseDouble(store_list.get(position).store_longitude),'K');
        //parameter=parameter.substring(0,parameter.length()-1);
        //holder.txt_distance.setText(parameter+" km");
        result_arr=new float[1];
        Location.distanceBetween(current_latitude, current_longitude, Double.parseDouble(store_list.get(position).store_latitude), Double.parseDouble(store_list.get(position).store_longitude), result_arr);

        Float f=new Float((result_arr[0]*0.001f));
        Double d=new Double(Float.toString(f));
        NumberFormat number = NumberFormat.getNumberInstance();
        number.setMaximumFractionDigits(3);
        String snum=number.format(d);
        holder.txt_distance.setText(snum+" km");

        if(store_list.get(position).store_priority.equals("yes"))
        {
            //holder.priority_star.setLayoutParams(new RelativeLayout.LayoutParams(50,50));
            holder.priority_star.setImageResource(R.drawable.yes);
        }
        else if(store_list.get(position).store_priority.equals("no"))
        {
            holder.priority_star.setImageResource(android.R.color.transparent);
            //holder.priority_star.setLayoutParams(new RelativeLayout.LayoutParams(0,0));
        }

        holder.root_store_name_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Store_data item=(Store_data)((RelativeLayout)v).getTag();
                Bundle b=new Bundle();
                b.putSerializable("store_details",item);
                Intent i=new Intent(context,StoreFinal.class);
                i.putExtras(b);
                context.startActivity(i);


            }
        });

        return convertView;
    }
    static class DetailsHolder {
        TextView txt_store_specific_name;
        RelativeLayout root_store_name_layout;
        ImageView store_name;
        TextView txt_distance;
        ImageView priority_star;
        }
    //public String getDistance(double lat1, double lon1, double lat2, double lon2) {
//        String result_in_kms = "";
//        String url = "http://maps.google.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1 + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
//        String tag[] = {"text"};
//        HttpResponse response = null;
//        try {
//            HttpClient httpClient = new DefaultHttpClient();
//            HttpContext localContext = new BasicHttpContext();
//            HttpPost httpPost = new HttpPost(url);
//            response = httpClient.execute(httpPost, localContext);
//            InputStream is = response.getEntity().getContent();
//            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//            org.w3c.dom.Document doc = builder.parse(is);
//            if (doc != null) {
//                NodeList nl;
//                ArrayList args = new ArrayList();
//                for (String s : tag) {
//                    nl = doc.getElementsByTagName(s);
//                    if (nl.getLength() > 0) {
//                        Node node = nl.item(nl.getLength() - 1);
//                        args.add(node.getTextContent());
//                    } else {
//                        args.add(" - ");
//                    }
//                }
//                result_in_kms =String.valueOf( args.get(0));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        //Float f=Float.valueOf(result_in_kms);
//        return result_in_kms;
//      android.location.Location homeLocation = new android.location.Location("");
//        homeLocation .setLatitude(lat1);
//        homeLocation .setLongitude(lon1);
//
//        android.location.Location targetLocation = new android.location.Location("");
//        targetLocation .setLatitude(lat2);
//        targetLocation .setLongitude(lon2);
//
//         float distanceInMeters =  targetLocation.distanceTo(homeLocation);
//         return String.valueOf((distanceInMeters*0.001));
    //}
//  private double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
//        double theta = lon1 - lon2;
//        double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
//        dist = Math.acos(dist);
//        dist = rad2deg(dist);
//        dist = dist * 60 * 1.1515;
//        if (unit == 'K') {
//          dist = dist * 1.609344;
//        } else if (unit == 'N') {
//          dist = dist * 0.8684;
//          }
//        return (dist);
//      }
//
//      /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
//      /*::  This function converts decimal degrees to radians             :*/
//      /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
//      private double deg2rad(double deg) {
//        return (deg * Math.PI / 180.0);
//      }
//
//      /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
//      /*::  This function converts radians to decimal degrees             :*/
//      /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/
//      private double rad2deg(double rad) {
//        return (rad * 180.0 / Math.PI);
//      }
    @Override
    public Filter getFilter() {

        return filter;
    }
    public class filter_here extends Filter{
        //ArrayList<String> Names=new ArrayList<String>(); 
        ArrayList<String> store_names;
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            // TODO Auto-generated method stub
             store_names=new ArrayList<String>();
            for(int i=0;i<store_list.size();i++)
            {
                store_names.add(store_list.get(i).store_name);
            }
            FilterResults Result = new FilterResults();
            // if constraint is empty return the original names
            if(constraint.length() == 0 ){
                Result.values = store_names;
                Result.count = store_names.size();
                return Result;
            }

            ArrayList<String> Filtered_Names = new ArrayList<String>();
            String filterString = constraint.toString().toLowerCase();
            String filterableString;

            for(int i = 0; i<store_list.size(); i++){
                filterableString = store_list.get(i).store_name;
                if(filterableString.toLowerCase().contains(filterString)){
                    Filtered_Names.add(filterableString);
                }
            }
            Result.values = Filtered_Names;
            Result.count = Filtered_Names.size();

            return Result;
        }

        @Override
        protected void publishResults(CharSequence constraint,FilterResults results) {
            // TODO Auto-generated method stub
            store_names = (ArrayList<String>) results.values;
            notifyDataSetChanged();
        }

    }
}
txtsearcher.addTextChangedListener(new TextWatcher() {

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

                StoreDetails.this.cdadp.getFilter().filter(s);

            }

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

            }

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

            }
        });
    public class filter_here extends Filter{
        //ArrayList<String> Names=new ArrayList<String>(); 
        //ArrayList<Store_data> store_list;
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            // TODO Auto-generated method stub
             //store_list=new ArrayList<Store_data>();
//          for(int i=0;i<store_list.size();i++)
//          {
//              store_names.add(store_list.get(i).store_name);
//          }
            FilterResults Result = new FilterResults();
            // if constraint is empty return the original names
            if(constraint.length() == 0 ){
                Result.values = store_list;
                Result.count = store_list.size();
                return Result;
            }

            ArrayList<Store_data> Filtered_Names = new ArrayList<Store_data>();
            String filterString = constraint.toString().toLowerCase();
            String filterableString;

            for(int i = 0; i<store_list.size(); i++){
                filterableString = store_list.get(i).store_name.toString();
                if(filterableString.toLowerCase().contains(filterString)){
                    Filtered_Names.add(store_list.get(i));
                }
            }
            Result.values = Filtered_Names;
            Result.count = Filtered_Names.size();

            return Result;
        }

        @Override
        protected void publishResults(CharSequence constraint,FilterResults results) {
            // TODO Auto-generated method stub
            store_list = (ArrayList<Store_data>) results.values;
            notifyDataSetChanged();
        }

    }