如何在android中的自定义ListView中实现搜索?

时间:2018-01-12 06:41:10

标签: android json listview search filter

我的应用程序中有一个edittext和listview我的listview显示联系人列表。我想要使​​用edittext的listview过滤器。我在谷歌搜索了很多,并找到了一些考试,但没有一个在我这里工作,我的代码 我的自定义适配器

public class MainActivity extends AppCompatActivity {

private static final int CODE_GET_REQUEST = 1024;
private static final int CODE_POST_REQUEST = 1025;

EditText editTextHeroId, editTextName, editTextRealname, editTextComment;
Spinner spinnerTeam;
ProgressBar progressBar;
ListView listView;
Button buttonAddUpdate;
Button buttonScan;
SearchView searchView;
Adapter HeroAdapter;

private List<Hero> heroList = new ArrayList<Hero>();
boolean isUpdating = false;

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

    editTextHeroId = (EditText) findViewById(R.id.editTextHeroId);
    editTextName = (EditText) findViewById(R.id.editTextName);
    editTextRealname = (EditText) findViewById(R.id.editTextRealname);
    editTextComment = (EditText) findViewById(R.id.editTextComment);
    spinnerTeam = (Spinner) findViewById(R.id.spinnerTeamAffiliation);

    buttonAddUpdate = (Button) findViewById(R.id.buttonAddUpdate);
    buttonScan = (Button) findViewById(R.id.buttonScan);

    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    listView = (ListView) findViewById(R.id.listViewHeroes);
    listView.setTextFilterEnabled(true);
    heroList = new ArrayList<>();

    HeroAdapter adapter = new HeroAdapter(heroList);
    final ArrayAdapter<Hero> HeroAdapter = new ArrayAdapter<Hero>(this, R.layout.layout_hero_list, heroList);
    listView.setAdapter(adapter);

    editTextName.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
            HeroAdapter.getFilter().filter(cs);
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

        @Override
        public void afterTextChanged(Editable arg0) {}

    });

适配器

public class HeroAdapter extends ArrayAdapter<Hero> implements Filterable {

    List<Hero> heroList;

    public HeroAdapter(List<Hero> heroList) {
        super(MainActivity.this, R.layout.layout_hero_list, heroList);
        this.heroList = heroList;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = getLayoutInflater();
        View listViewItem = inflater.inflate(R.layout.layout_hero_list, null, true);

        final TextView textViewName = listViewItem.findViewById(R.id.textViewName);
        TextView textViewUpdate = listViewItem.findViewById(R.id.textViewUpdate);
        TextView textViewDelete = listViewItem.findViewById(R.id.textViewDelete);

        final Hero hero = heroList.get(position);

        textViewName.setText(hero.getName());

        textViewUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isUpdating = true;
                editTextHeroId.setText(String.valueOf(hero.getId()));
                editTextName.setText(hero.getName());
                editTextRealname.setText(hero.getRealname());
                editTextComment.setText(hero.getRating());
                spinnerTeam.setSelection(((ArrayAdapter<String>) spinnerTeam.getAdapter()).getPosition(hero.getTeamaffiliation()));
                buttonAddUpdate.setText("Update");
            }
        });

        textViewDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

                builder.setTitle("Delete " + hero.getName())
                        .setMessage("Are you sure you want to delete it?")
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                deleteHero(hero.getId());
                            }
                        })
                        .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        })
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .show();
            }
        });
        return listViewItem;
    }

    public Filter getFilter() {

        Filter filter = new Filter() {

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

                heroList = (List<Hero>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<Hero> heroList = new ArrayList<Hero>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < heroList.size(); i++) {
                    Hero dataNames = heroList.get(i);
                    if (dataNames.toString().toLowerCase().startsWith(constraint.toString()))  {
                        heroList.add(dataNames);
                    }
                }

                results.count = heroList.size();
                results.values = heroList;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

当我从edittext填充关键字时,列表数据无法显示,。任何帮助都会得到满足。提前谢谢

3 个答案:

答案 0 :(得分:0)

heroList.size()始终为0,因此不会进入&#34; for(int i = 0; i&lt; heroList.size(); i ++)&#34;在所有

你必须删除&#34; ArrayList heroList = new ArrayList();&#34;选择GLOBAL heroList。

protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults results = new FilterResults();
            **ArrayList<Hero> heroList = new ArrayList<Hero>();**

            // perform your search here using the searchConstraint String.

            constraint = constraint.toString().toLowerCase();
            for (int i = 0; i < heroList.size(); i++) {
                Hero dataNames = heroList.get(i);
                if (dataNames.toString().toLowerCase().startsWith(constraint.toString()))  {
                    heroList.add(dataNames);
                }
            }

            results.count = heroList.size();
            results.values = heroList;
            Log.e("VALUES", results.values.toString());

            return results;
        }

答案 1 :(得分:0)

首先,在活动的顶部

Adapter HeroAdapter;

应该是

HeroAdapter adapter;

然后你需要实际初始化那个一个,而不是一个不同的适配器,甚至两个

this.heroList = new ArrayList<>();
this.adapter = new HeroAdapter(this, heroList);
listView.setAdapter(adapter);

修复适配器的构造函数以接受Context而不是耦合到MainActivity

public class HeroAdapter extends ArrayAdapter<Hero> implements Filterable {

    private List<Hero> heroList;

    public HeroAdapter(Context c, List<Hero> heroList) {
        super(c, R.layout.layout_hero_list, heroList);
        this.heroList = heroList;
    }

然后你也会&#34;影子&#34;当您尝试过滤时,您的列表为空。如果您阅读警告,Android Studio甚至可能会指出这一点。

将其重命名为其他内容

FilterResults results = new FilterResults();
List<Hero> filtered = new ArrayList<>();
constraint = constraint.toString().toLowerCase();
for (Hero h : MainActivity.this.heroList) {
     if (h.getName().toLowerCase().startsWith(constraint))  {
         filtered.add(h);
     }
 }

results.count = filtered.size();
results.values = filtered;
return results;

答案 2 :(得分:-2)

您在onTextChanged()方法中使用了适配器的类名,而不是适配器的对象。

试试这个:

 @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        String text = editTextName.getText().toString().toLowerCase(Locale.getDefault());
        adapter.filter(text);
    }