简体   繁体   English

如何在Android中过滤自定义ListAdapter?

[英]How to filter a custom ListAdapter in android?

I have searched a lot, but no any solutions are working for me. 我已经搜索了很多,但是没有任何解决方案对我有用。 I am seting a custom arrayadapter which has a imageview and a textview. 我正在设置具有imageview和textview的自定义arrayadapter。 I kept an edittext where i want to add text and i wish to get the list filtered by these given texts, When i use a string type array adapter this works great, but its not working in my custom adapter, here is my code: 我在要添加文本的位置保留了一个edittext,并希望通过这些给定的文本过滤列表,当我使用字符串类型数组适配器时,此方法效果很好,但在我的自定义适配器中不起作用,这是我的代码:

public class CurrenciesFrom extends Activity implements OnItemClickListener {

    ListView lvCurrencies;
    String[] countryCode = { "BDT Bangladesh","BBF bafa" ,"USD America", "UMK Umaka","KRW Korea",
            "INR India" };
    int[] flag = { R.drawable.bdt, R.drawable.usd, R.drawable.aud,
            R.drawable.ic_launcher ,R.drawable.usd, R.drawable.aud};
    ArrayAdapter<Currency> adapter;
    List<Currency> l;
    EditText etsearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.currencies);
        initializer();
        lvCurrencies.setAdapter(adapter);
        lvCurrencies.setOnItemClickListener(this);
        etsearch.addTextChangedListener(new TextWatcher() {

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

            }

            @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


                CurrenciesFrom.this.adapter.getFilter().filter(s.toString());
            }
        });
    }

    private List<Currency> getModel() {
        List<Currency> list = new ArrayList<Currency>();
        for (int i = 0; i < countryCode.length; i++) {

            list.add(get(countryCode[i], flag[i]));
        }

        list.get(1).setSelected(true); // select one item by default
        return list;
    }

    private Currency get(String s, int place) {
        return new Currency(s, place);
    }

    private void initializer() {

        lvCurrencies = (ListView) findViewById(R.id.lvCurrencies);
        etsearch=(EditText)findViewById(R.id.etSearch);
        lvCurrencies.setTextFilterEnabled(true);
        // countryCode = getResources().getStringArray(R.array.Currencies);
        l = getModel();

        Collections.sort(l, new Comparator<Currency>() {
            @Override
            public int compare(Currency c1, Currency c2) {
                return c1.getName().compareToIgnoreCase(c2.getName());
            }
        });

        adapter = new Customarrayadapter(this, l);
    }

My custom adapter class is: 我的自定义适配器类是:

package com.powergroupbd.yahoo;

import java.util.List;

import android.app.Activity;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

public class Customarrayadapter extends ArrayAdapter<Currency> {

    private final List<Currency> list;
    private final Activity context;

    public Customarrayadapter(Activity context, List<Currency> list) {
        super(context, R.layout.showlist, list);
        this.context = context;
        this.list = list;
    }

    static class ViewHolder {
        protected TextView text;
        protected ImageView sub;
        protected CheckBox checkbox;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.showlist, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.text = (TextView) view.findViewById(R.id.label);
            viewHolder.text.setTextColor(Color.WHITE);
            viewHolder.sub = (ImageView) view.findViewById(R.id.sub);

            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
            viewHolder.checkbox
                    .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView,
                                boolean isChecked) {
                            Currency element = (Currency) viewHolder.checkbox.getTag();
                            element.setSelected(buttonView.isChecked());
                            System.out.println("Checked : " + element.getName());
                        }
                    });
            view.setTag(viewHolder);
            viewHolder.checkbox.setTag(list.get(position));
        } else {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.text.setText(list.get(position).getName());
        holder.sub.setImageResource(list.get(position).getPlace());
        holder.checkbox.setChecked(list.get(position).isSelected());
        return view;
    }
}

Please help me :( 请帮我 :(

User this code, for filter the text 使用此代码,以过滤文本

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

    textlength = edittext.getText().length();
    text_sort.clear();
    image_sort.clear();

    for (int i = 0; i < text.length; i++)
    {
        if (textlength <= text[i].length())
        {
            if (edittext.getText().toString().
                    equalsIgnoreCase((String) text[i].subSequence(0, textlength)))
            {
                text_sort.add(text[i]);
                image_sort.add(image[i]);
            }
        }
    }

    listview.setAdapter(new MyCustomAdapter(text_sort, image_sort));

    }
}

for more, refer this site it may help you http://android-helper.blogspot.in/2011/07/android-search-in-custom-listview.html 有关更多信息,请访问此网站,它可能会对您有所帮助http://android-helper.blogspot.in/2011/07/android-search-in-custom-listview.html

The accepted answer is very misleading and ignores the actual problem. 公认的答案非常容易引起误解,并且忽略了实际问题。 The OP is incorrectly subclassing ArrayAdapter . OP错误地将ArrayAdapter子类化。 You should never track your own list of data and instead access that data through the proper adapter methods. 您永远不应跟踪自己的数据列表,而应通过适当的适配器方法访问该数据。 Eg, getItem(position) . 例如, getItem(position) The ArrayAdapter makes no guarentees that the List instance you pass into it stays the same. ArrayAdapter不保证您传入的List实例保持不变。

In fact, during a filter operation, it copies the data over to a new ArrayList instance. 实际上,在筛选操作期间,它将数据复制到新的ArrayList实例中。 That means your list used in the subclass is no longer referring to the same list in the ArrayAdapter . 这意味着您在子类中使用的列表不再引用ArrayAdapter的相同列表。 Since you are accessing your own list in the getView() method; 由于您正在使用getView()方法访问自己的列表,因此, instead of pulling from getItem() , any filtering changes will be missed. 而不是从getItem()提取,所有筛选更改都将丢失。 In fact by this point, you also broke the ability to add or remove from the adapter as well. 实际上,到此为止,您还破坏了在适配器中添加或删除适配器的功能。

Most important rule when subclassing ArrayAdapter . 子类化ArrayAdapter时最重要的规则。 Never keep an external list of data. 切勿保留外部数据列表。 Always refer into the ArrayAdapter instead. 始终改为引用ArrayAdapter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM