Android 如何通过 EditText 过滤 ListView

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10355971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:25:06  来源:igfitidea点击:

How to Filter ListView through EditText

androiddatabaselistviewfiltercursor

提问by Mordiggian

Im making an eBook like application for android and i want to filter the title of the book but everytime that you put a word or sentence in the edittext it will search the content of the books... can someone help me with this...

我正在制作一个类似 android 应用程序的电子书,我想过滤书名,但每次你在编辑文本中输入一个单词或句子时,它都会搜索书的内容......有人可以帮我吗......

回答by Mehul Joisar

try this one,whenever u enter text in the edittext ,the list will show filtered result as i have shown the stuff in images

试试这个,每当你在编辑文本中输入文本时,列表将显示过滤结果,因为我已经在图像中显示了内容

Initial:

最初的:

Initial

最初的

Filtered:

过滤:

Filtered:
this is main.xml

过滤:
这是 main.xml

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

<EditText 
    android:id="@+id/etSearchbox"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
<ListView 
    android:id="@+id/lvFirst"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"

    ></ListView>    

</LinearLayout>

this is FilterListActivity.java

这是 FilterListActivity.java

package com.filterlist;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class FilterListActivity extends Activity{

EditText etSearchbox;
ListView lvFirst;
ArrayAdapter<String> adapter1;
String[] data = {"mehul joisar","amit mishra","amitabh","Aamir khan","jesica","katrina"};

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

etSearchbox=(EditText)findViewById(R.id.etSearchbox);
lvFirst=(ListView)findViewById(R.id.lvFirst);
lvFirst.setTextFilterEnabled(true);

adapter1 = new ArrayAdapter<String>(FilterListActivity.this, android.R.layout.simple_list_item_1, data);   
lvFirst.setAdapter(adapter1);

etSearchbox.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
        // TODO Auto-generated method stub
        FilterListActivity.this.adapter1.getFilter().filter(arg0);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
            int arg3) {
        // TODO Auto-generated method stub

    }

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

    }
});




}
}

回答by Chronos

I have a working example, try this:

我有一个工作示例,试试这个:

filterEditText = (EditText)findViewById(R.id.filter);
filterEditText.addTextChangedListener(filterTextWatcher);

TextWatcher filterTextWatcher = new TextWatcher() {

        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);
        }

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

The adapter must implements Filterable

适配器必须 implements Filterable

            @Override
            public Filter getFilter() {
//              Filter filter = null;

                if(filter == null)
                    filter = new CheeseFilter();
                return filter;
            }

And the filter class:

和过滤器类:

        public class CheeseFilter extends Filter {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                // TODO Auto-generated method stub

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

                FilterResults newFilterResults = new FilterResults();

                if (constraint != null && constraint.length() > 0) {


                    ArrayList<String> auxData = new ArrayList<String>();

                    for (int i = 0; i < data.size(); i++) {
                        if (data.get(i).toLowerCase().contains(constraint))
                            auxData.add(data.get(i));
                    }

                    newFilterResults.count = auxData.size();
                    newFilterResults.values = auxData;
                } else {

                    newFilterResults.count = data.size();
                    newFilterResults.values = data;
                }

                return newFilterResults;
            }

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

                ArrayList<String> resultData = new ArrayList<String>();

                resultData = (ArrayList<String>) results.values;

                EfficientAdapter adapter = new EfficientAdapter(context, resultData);
                list.setAdapter(adapter);

//              notifyDataSetChanged();
            }

        }

You can check this post for more info:

您可以查看此帖子以获取更多信息:

Filter expandableList

过滤 expandableList

Filter ListView

过滤列表视图

回答by H.Fa8

when you use Custom listView

当您使用自定义列表视图

Adapter :

适配器 :

public class Adapter extends ArrayAdapter {
ArrayList<String> list = new ArrayList<>();
ArrayList<String> filteredData = new ArrayList<>();

public Adapter(@NonNull Context context, int resource) {
    super(context, resource);
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    LayoutInflater inflate = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    @SuppressLint("ViewHolder") View vi = inflate.inflate(R.layout.ly_items, null);
    try {
        JSONObject js = new JSONObject(list.get(position));
        TextView txtItem = vi.findViewById(R.id.txtItem);
        ImageView imgItem = vi.findViewById(R.id.imgItem);
        txtItem.setText(js.getString("name") + " - " + js.getInt("number"));
        Picasso.get().load(js.getString("logo_url")).into(imgItem);

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

    return vi;
}

@Override
public void add(@Nullable Object object) {
    super.add(object);
    list.add(object.toString());
    filteredData.add(object.toString());
}

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

@Nullable
@Override
public Object getItem(int position) {
    return list.get(position);
}


public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    list.clear();
    if (charText.length() == 0) {
        list.addAll(filteredData);
    } else {
        for (String wp : filteredData) {

            try {
                JSONObject json = new JSONObject(wp);
                if (json.getString("name").toLowerCase().contains(charText) || json.getString("number").contains(charText)) {
                    list.add(wp);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    notifyDataSetChanged();
    }
}

And your class:

还有你的班级:

    Adapter adapter;
ListView list;
EditText edtSearch;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

list = findViewById(R.id.list);

edtSearch = findViewById(R.id.edtSearch);

 adapter = new Adapter(this, android.R.layout.simple_list_item_1);


list.setAdapter(adapter);

edtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

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

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

    }

回答by kosa

You need write textChangedlistener (or) TextWatcher for the edittext. Inside the listener you need to write search logic. Here is APIdoc. Here is an example on textwatcher.

您需要为编辑文本编写 textChangedlistener(或)TextWatcher。在侦听器中,您需要编写搜索逻辑。这是APIdoc。这是一个关于textwatcher的例子。