SearchView过滤和设置建议

时间:2014-11-06 17:56:34

标签: android filtering searchview search-suggestion

我很擅长使用SearchView。我需要一个功能,我有一个ActionBar,我有Search。点击“搜索”后,建议应显示在“搜索”字段下方的列表中。

到目前为止我做了什么: 在menu.xml中添加了搜索,并在onCreateOptionsMenu()中编写了代码,我在其中初始化了SearchView,setSuggestionsAdapter也实现了setOnQueryTextListener

结果:我进入应用程序,点击搜索图标,显示建议。我输入一个字母,对匹配的字母进行排序。我键入第二个字母,它没有显示建议。我也关闭了searchview并再次打开它,键盘打开了,但列表中的建议没有显示。

我需要什么:根据用户输入的字符进行过滤。即使它不止一个角色。 始终显示建议,默认为一个包含所有列表项,或者是在用户键入时排序的建议。

我在Android的SearchView类中看到,他们将文本设置为空并且也忽略了建议。但我不想要这个。

我被困在这里,不知道如何继续。请帮我。 这是我的适配器代码:

public class ExampleAdapter extends CursorAdapter implements Filterable {

    private ArrayList<String> items;
    private ArrayList<String> orig;

    public ExampleAdapter(Context context, Cursor cursor,
            ArrayList<String> items) {
        super(context, cursor, false);
        this.items = new ArrayList<String>();
        this.items = items;
        orig = new ArrayList<String>();
        orig.addAll(items);
    }

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

    @Override
    public Filter getFilter() {
        return new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                constraint = constraint.toString().toLowerCase();
                FilterResults result = new FilterResults();

                if (constraint != null
                        && constraint.toString().length() > 0) {
                    List<String> founded = new ArrayList<String>();
                    for (int i = 0, l = orig.size(); i < l; i++) {
                        if (orig.get(i)
                                .toString()
                                .toLowerCase()
                                .startsWith(
                                        constraint.toString().toLowerCase()))
                            founded.add(orig.get(i));
                    }

                    result.values = founded;
                    result.count = founded.size();
                } else {
                    synchronized (this) {
                        result.values = orig;
                        result.count = orig.size();
                    }

                }
                return result;

            }

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

                items.clear();
                items = new ArrayList<String>();
                items = (ArrayList<String>) results.values;
                notifyDataSetChanged();

            }

        };
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.textView.setText(items.get(cursor.getPosition()));
    }

    public class ViewHolder {
        public TextView textView;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        ViewHolder holder = new ViewHolder();
        View v = null;

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        v = inflater.inflate(R.layout.item, parent, false);
        holder.textView = (TextView) v.findViewById(R.id.text);

        v.setTag(holder);
        return v;

    }
}

我的活动中与我有searchview的菜单相关的代码:

private String[] columns = new String[] { "_id", "text" };
    private SearchView searchView;
    private SearchManager manager;
    private ExampleAdapter aptr;

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

    manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

}

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
        setSearchTextColour(searchView);
        setSearchIcons(searchView);
        searchView.setQueryHint(Html.fromHtml("<font color = #ffffff>"
                + getResources().getString(R.string.search_store) + "</font>"));
        searchView.setSearchableInfo(manager
                .getSearchableInfo(getComponentName()));
        Object[] temp = new Object[] { 0, "default" };
        final MatrixCursor cursor = new MatrixCursor(columns);
        for (int i = 0; i < alStoreNames.size(); i++) {
            temp[0] = i;
            temp[1] = alStoreNames.get(i);
            cursor.addRow(temp);
        }
        aptr = new ExampleAdapter(MainActivity.this, cursor, alStoreNames);
        searchView.setSuggestionsAdapter(aptr);

    searchView.setOnQueryTextListener(new OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String arg0) {
            if (!TextUtils.isEmpty(arg0)) {
                aptr.getFilter().filter(arg0.toString());
            }
            return true;
        }

        @Override
        public boolean onQueryTextChange(String arg0) {
            return false;
        }
    });

    searchView.setOnSuggestionListener(new OnSuggestionListener() {

            @Override
            public boolean onSuggestionSelect(int arg0) {
                return false;
            }

            @Override
            public boolean onSuggestionClick(int position) {
                String suggestion = getSuggestion(position);
                db.openDatabase();
                String studentId = db.getStudentIdFromName(suggestion);
                String studentImg = db.getStudentImgFromName(suggestion);
                db.closeDatabase();
                Log.e("Sp", " On Click name -> " + aptr.getItem(position).toString() + " : "
                         + aptr.getCursor().getString(0) + " : " + suggestion);
                Intent i = new Intent(MainActivity.this,
                        ExampleActivity.class);
                i.putExtra("studentId", studentId);
                i.putExtra("studentName", suggestion);
                i.putExtra("studentImg", studentImg);
                startActivity(i);
                return true;
            }
        });

    return true;
}

private String getSuggestion(int position) {
    Cursor cursor = (Cursor) searchView.getSuggestionsAdapter().getItem(
            position);
    String suggest1 = cursor.getString(cursor.getColumnIndex("text"));
    return suggest1;
}

private void setSearchTextColour(SearchView searchView) {
        Field qTextField;
        try {
            qTextField = SearchView.class.getDeclaredField("mQueryTextView");
            qTextField.setAccessible(true);
            SearchAutoComplete searchPlate = (SearchAutoComplete) qTextField
                    .get(searchView);
            searchPlate.setTextColor(getResources().getColor(R.color.white));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

private void setSearchIcons(SearchView searchView) {
    try {
        Field searchField = SearchView.class
                .getDeclaredField("mCloseButton");
        searchField.setAccessible(true);
        ImageView closeBtn = (ImageView) searchField.get(searchView);
        closeBtn.setImageResource(R.drawable.close);

        Field searchField1 = SearchView.class
                .getDeclaredField("mSearchButton");
        searchField1.setAccessible(true);
        ImageView searchButton = (ImageView) searchField1.get(searchView);
        searchButton.setImageResource(R.drawable.ic_action_search);

    } catch (NoSuchFieldException e) {
        Log.e("SearchView", e.getMessage(), e);
    } catch (IllegalAccessException e) {
        Log.e("SearchView", e.getMessage(), e);
    }
}

3 个答案:

答案 0 :(得分:2)

您好我发现您的代码有些问题。 请试试我的方式。 替换publishResults of ExampleAdapter

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

                items.clear();
                 // items = new ArrayList<String>();
                //items = (ArrayList<String>) results.values;
                items.addAll((ArrayList<String>) results.values);
                notifyDataSetChanged();

            }

    searchView.setOnQueryTextListener(new OnQueryTextListener() {

        @Override
        public boolean onQueryTextSubmit(String arg0) {
            if (!TextUtils.isEmpty(arg0)) {
                aptr.getFilter().filter(arg0.toString());
            }
            return true;
        }

        @Override
        public boolean onQueryTextChange(String arg0) {
if (!TextUtils.isEmpty(arg0)) {
                aptr.getFilter().filter(arg0.toString());
return true;
            }
            return false;
        }
    });

答案 1 :(得分:2)

在我看来,问题的一部分是缺少getItem()方法。

如果查看游标适配器源代码,getItem()将从游标中获取数据,而不是从过滤后的列表中获取数据,您希望它从过滤后的列表中获取数据!

试试这个:

@Override
 public Object getItem(int position) {
    if (position < items.size()) {            
        return items.get(position);
    } else {
        return null;
    }
}

我忘了添加,你还需要改变这个:

private String getSuggestion(int position) {
    String suggest1 = (String) searchView.getSuggestionsAdapter().getItem(position);    
    return suggest1;
}

要关闭所有内容,请先将其添加到createOptions菜单:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    searchView = (SearchView) MenuItemCompat.getActionView(searchItem);

    searchView.setIconifiedByDefault(true); //this line

    ...

然后将此添加到onSuggestionClick:

 @Override
 public boolean onSuggestionClick(int position) {
   String suggestion = getSuggestion(position);
   db.openDatabase();
   String studentId = db.getStudentIdFromName(suggestion);
   String studentImg = db.getStudentImgFromName(suggestion);
   db.closeDatabase();
   Log.e("Sp", " On Click name -> " + aptr.getItem(position).toString() + " : "
        + aptr.getCursor().getString(0) + " : " + suggestion);

   searchView.setIconified(true);//this line


   Intent i = new Intent(MainActivity.this,ExampleActivity.class);
   i.putExtra("studentId", studentId);
   i.putExtra("studentName", suggestion);
   i.putExtra("studentImg", studentImg);
   startActivity(i);
   return true;
}

一点解释。当您调用setIconified时,它将清除searchView的文本或将其折叠,具体取决于默认状态。我们在那里做的是将默认状态设置为图标化,因此当我们调用setIconified方法时,它将清除文本并折叠视图!

答案 2 :(得分:0)

尝试将搜索值传递给过滤器,即使是空的:

@Override
public boolean onQueryTextSubmit(String arg0) {
     aptr.getFilter().filter(arg0.toString());
     return true;
}

如果搜索不匹配或搜索值为空,则将默认列表设置为适配器:

@Override
public Filter getFilter() {
   return new Filter() {
   @Override
   protected FilterResults performFiltering(CharSequence constraint) {
      constraint = constraint.toString().toLowerCase();
      FilterResults result = new FilterResults();

      if (constraint != null && constraint.toString().length() > 0) {
          List<String> founded = new ArrayList<String>();
          for (int i = 0, l = orig.size(); i < l; i++) {
               if (orig.get(i).toString().toLowerCase().startsWith(constraint.toString().toLowerCase()))
                            founded.add(orig.get(i));
          }

          if(founded.size()>0){
             result.values = founded;
             result.count = founded.size();
          }else{
             result.values = orig;
             result.count = orig.size();
          }
      } else {
             result.values = orig;
             result.count = orig.size();
      }
      return result;

}