为Listview设置过滤器有什么错误

时间:2012-04-29 20:32:24

标签: android layout android-activity filter

我有一个模型类,它包含不同的项目,如字符串和图像URL。

我为此实现了一个过滤器,但不幸的是,每当我搜索时,所有项目都会消失。帮助我如何实现过滤器。

这是源代码。

package Dummy.list.filter;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;

public class DummyListFilterActivity extends Activity {
    /** Called when the activity is first created. */


    myadapter adapter;
    EditText filterText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        ModelClass[] str = new ModelClass[]{new ModelClass("cell",R.drawable.ic_launcher,1), 
                new ModelClass("Bus",R.drawable.ic_launcher,2),
                new ModelClass("Car",R.drawable.ic_launcher,3),
                new ModelClass("Van",R.drawable.ic_launcher,4),
                new ModelClass("Lorry",R.drawable.ic_launcher,5)};

        ListView list = (ListView)findViewById(R.id.Service_name_list);
        filterText = (EditText)findViewById(R.id.txtUserName);
        filterText.addTextChangedListener(filterTextWatcher);

        list.setTextFilterEnabled(true);

        adapter = new myadapter(this, 0, str); 

       //ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,str);

        list.setAdapter(adapter);

    }

    private TextWatcher filterTextWatcher = new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

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

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            adapter.getFilter().filter(s.toString());
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        filterText.removeTextChangedListener(filterTextWatcher);
    }

}

这是我的Adapter类的外观

package Dummy.list.filter;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;


    public class myadapter extends ArrayAdapter<ModelClass>
    {

        //private final List<String> contactNumbers;
            //private final String[] contactDetails;
            private final ModelClass[] contactDetails;
            private final Activity AdapterContext;


        public myadapter(Context context, int textViewResourceId,ModelClass[] objects) 
        {
            super(context, textViewResourceId, objects);
            // TODO Auto-generated constructor stub
            contactDetails = objects;
            AdapterContext = (Activity) context;
        }

        static class ViewHolder {
            protected TextView ContactNumbers;
            protected ImageView ContactImage;
        }

        public View getView(int position, View convertView, ViewGroup parent)
        {
            View view = null;
            if(convertView == null)
            {
                LayoutInflater inflator = AdapterContext.getLayoutInflater();
                view = inflator.inflate(R.layout.item, null);

                final ViewHolder holder = new ViewHolder();
                holder.ContactImage = (ImageView) view.findViewById(R.id.image);
                holder.ContactNumbers = (TextView) view.findViewById(R.id.text);    
                view.setTag(holder);
            }
            else
            {
                view = convertView;
            }

            ViewHolder holder = (ViewHolder) view.getTag();
            holder.ContactNumbers.setText(contactDetails[position].getServiceName());
            holder.ContactImage.setImageResource(contactDetails[position].getServiceImage());
            view.setTag(holder);
            return view;

        }

    }

1 个答案:

答案 0 :(得分:0)

您的适配器应该实现Filterable。将myadapter类替换为以下类:

public class myadapter extends ArrayAdapter<ModelClass> implements Filterable
{

    //private final List<String> contactNumbers;
    //private final String[] contactDetails;
    private ModelClass[] contactDetails;
    private ModelClass[] original;
    private final Activity AdapterContext;
    private Filter filter;
    private Object lock = new Object();


    public myadapter(Context context, int textViewResourceId,ModelClass[] objects) 
    {
        super(context, textViewResourceId, objects);
        // TODO Auto-generated constructor stub
        contactDetails = original = objects;
        AdapterContext = (Activity) context;
    }

    static class ViewHolder {
        protected TextView ContactNumbers;
        protected ImageView ContactImage;
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
        View view = null;
        if(convertView == null)
        {
            LayoutInflater inflator = AdapterContext.getLayoutInflater();
            view = inflator.inflate(R.layout.item, null);

            final ViewHolder holder = new ViewHolder();
            holder.ContactImage = (ImageView) view.findViewById(R.id.image);
            holder.ContactNumbers = (TextView) view.findViewById(R.id.text);    
            view.setTag(holder);
        }
        else
        {
            view = convertView;
        }

        ViewHolder holder = (ViewHolder) view.getTag();
        holder.ContactNumbers.setText(contactDetails[position].getServiceName());
        holder.ContactImage.setImageResource(contactDetails[position].getServiceImage());
        view.setTag(holder);
        return view;

    }

    @Override
    public Filter getFilter() {
    // TODO Auto-generated method stub
    if (filter == null) {
        filter = new MyFilter();
    }
    return filter;
    }

    private class MyFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
        // TODO Auto-generated method stub
        String query = constraint.toString().toLowerCase();
        FilterResults results = new FilterResults();
        ModelClass[] temp;
        synchronized (lock) {
                temp = Arrays.copyOf(contactDetails, contactDetails.length);
        }
        if (query == null || query.length() == 0) {
            synchronized (lock) {
            results.values = original;
                results.count = original.length;
            }
        } else {
            ModelClass[] filtered = new ModelClass[original.length];
            int size = 0;
            for (int i = 0; i < temp.length; i++) {
            ModelClass content = temp[i];
            if(content.getServiceName().equalsIgnoreCase(query)) {
                filtered[size++] = content;
            }
        }
        filtered = Arrays.copyOf(filtered, size);
        results.values = filtered;
        results.count = filtered.length;
        }
        return results;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void publishResults(CharSequence constraint,
            FilterResults results) {
        // TODO Auto-generated method stub
        contactDetails = (ModelClass[]) results.values;
        notifyDataSetChanged();
    }

    }
}

我还没有测试过。但我希望它能奏效。