项目在Android Studio中的SearchView工具栏界面中未显示弹出。

huangapple go评论74阅读模式
英文:

items are not popping up in the SearchView toolbar interface Android Studio java

问题

大家好,我想在我的工具栏上实现一个搜索界面,以便在我的网格视图中搜索项目。然而,它出现在我的工具栏上,但是当我点击搜索图标并开始输入时,没有弹出任何内容。我对当前问题的所在地感到困惑。我使用了自定义适配器,因此我认为需要更多的工作。

以下是我的自定义 ArrayAdapter 类(WordAdapter)的部分代码,聚焦于 getView() 函数之后,因为我认为那是类中最相关的部分。我还添加了一些全局变量,如 ArrayList<> list 和 listFull,因为我认为我需要整个项目列表的副本,但老实说,我不太确定如何处理这个。

public class WordAdapter extends ArrayAdapter<WordFolder> implements Filterable {

    // 控制复选框是否可见的变量
    private boolean displayCheckBox;
    private ArrayList<WordFolder> original_list;
    private ArrayList<WordFolder> new_list;

    // 构造函数 - 接受上下文和单词列表
    WordAdapter(Context context, ArrayList<WordFolder> word){
        super(context, 0, word);

        // 创建包含所有文件夹名称的 ArrayList 的副本
        original_list = new ArrayList<>(word);
        new_list = new ArrayList<>(word);
    }

    // 设置复选框的可见性
    public void setCheckBoxVisibility(boolean visible){
        this.displayCheckBox = visible;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        // ... 省略部分代码 ...

        return listItemView;
    }

    @NonNull
    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                // ... 省略部分代码 ...
                return results;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
                new_list.clear();
                new_list.addAll((ArrayList) filterResults.values);
                notifyDataSetChanged();
            }
        };
        return filter;
    }
}

以下是我在 MainActivity 中为搜索界面创建的代码部分,供您参考。顺便提一下,itemadapter 是我的自定义适配器变量的名称。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // 初始化菜单膨胀器
    MenuInflater inflater = getMenuInflater();
    if (whichToolbar == 0) {
        // 膨胀菜单
        inflater.inflate(R.menu.menu_search, menu);
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(false);

        MenuItem searchItem = menu.findItem(R.id.search);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                itemAdapter.getFilter().filter(s);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                itemAdapter.getFilter().filter(newText);
                return true;
            }
        });
        searchView.setOnCloseListener(new SearchView.OnCloseListener() {
            @Override
            public boolean onClose() {
                itemAdapter.getFilter().filter("");
                return false;
            }
        });
    } else {
        inflater.inflate(R.menu.delete_menu, menu);
    }
    return true;
}

我更新了这部分内容,因为问题还没有得到答复。我一直在关注并观看关于此问题的 YouTube 视频(不只是一个视频),并查阅了 Android 开发者指南,确保代码“有效”,但是目前我的搜索栏没有任何作用。

英文:

Hello guys I want to implement a Search interface on my Toolbar to search items in my GridView. However it appears on my Toolbar but when I click the search icon and start typing, nothing pops up. I'm lost on where the issue currently is. I use a custom adapter so I believe there is it bit more work into it.

Here is my custom ArrayAdapter class (WordAdapter). Focus the stuff after the getView() function since I believe that's the most relevant part of the class. I also added some global variables such as ArrayList<> list and listFull since I believe I needed some copy of my entire item list but honestly I wasn't sure on how to go about that.


//variable responsible for making checkbox visible or not
private boolean displayCheckBox;
private ArrayList&lt;WordFolder&gt; original_list;
private ArrayList&lt;WordFolder&gt; new_list;
//constructor - it takes the context and the list of words
WordAdapter(Context context, ArrayList&lt;WordFolder&gt; word){
super(context, 0, word);
//creating a copy of the ArrayList containing all the folders name
original_list = new ArrayList&lt;&gt;(word);
new_list = new ArrayList&lt;&gt;(word);
}
//sets the visibility of the checkBox
public void setCheckBoxVisibility(boolean visible){
this.displayCheckBox = visible;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if(listItemView == null){
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.folder_view, parent, false);
}
//getting the checkBox view id
CheckBox checkBox = (CheckBox) listItemView.findViewById(R.id.check_box);
checkBox.setVisibility(displayCheckBox ? View.VISIBLE : View.GONE);
//Getting the current word
final WordFolder currentWord = getItem(position);
//making the 3 text view to match our word_folder.xml
TextView date_created = (TextView) listItemView.findViewById(R.id.date_created);
TextView title = (TextView) listItemView.findViewById(R.id.title);
TextView desc = (TextView) listItemView.findViewById(R.id.desc);
//using the setText to get the text and set it in the textView
date_created.setText(currentWord.getDateCreated());
title.setText(currentWord.getTitle());
desc.setText(currentWord.getTitleDesc());
//call automatically when checkbox is changed
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
@Override
//compound button = the view of the button
//b = the new state of the checkbox
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//set the value of the checkbox to the CurrentWord
currentWord.setChecked(b);
}
});
return listItemView;
}
@NonNull
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults filterResults = new FilterResults();
if (charSequence == null || charSequence.length() == 0) {
filterResults.count = original_list.size();
filterResults.values = original_list;
} else {
String searchStr = charSequence.toString().toLowerCase();
ArrayList&lt;WordFolder&gt; results = new ArrayList&lt;&gt;();
for (WordFolder item : original_list) {
if (item.getTitle().contains(searchStr)) {
results.add(item);
}
filterResults.count = results.size();
filterResults.values = results;
}
}
//new list which contains only filtered items
ArrayList&lt;WordFolder&gt; filteredList = new ArrayList&lt;&gt;();
if(charSequence == null || charSequence.length() == 0){
filteredList.addAll(original_list);
}
else{
String filterPattern = charSequence.toString().toLowerCase().trim();
for(WordFolder item : original_list){
if(item.getTitle().toLowerCase().contains(filterPattern)){
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
new_list.clear();
new_list.addAll((ArrayList) filterResults.values);
notifyDataSetChanged();
}
};
return filter;
}
}

Here is the part of the code in my MainActivity that I created the Search interface for reference. Btw itemadapter is the name of my custom adapter variable

    public boolean onCreateOptionsMenu(Menu menu) {
// initialize menu inflater
MenuInflater inflater = getMenuInflater();
if(whichToolbar == 0){
//inflate menu
inflater.inflate(R.menu.menu_search, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
//initialize menu item
MenuItem searchItem = menu.findItem(R.id.search);));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
itemAdapter.getFilter().filter(s);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
itemAdapter.getFilter().filter(newText);
return true;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
itemAdapter.getFilter().filter(&quot;&quot;);
return false;
}
});
}
else{
inflater.inflate(R.menu.delete_menu, menu);
}
return true;
}

I updated this since question hasn't been answered. I've been following and watching Youtube videos (not just 1 vid) and the android developer guide about this and made sure the code was "working" and yet my search bar does not do anything at the moment.

答案1

得分: 0

在您的适配器中使用以下内容:

private ArrayList<WordFolder> actualdata = new ArrayList<WordFolder>();
private ArrayList<WordFolder> orignallist = new ArrayList<>();

WordAdapter(Context context, ArrayList<WordFolder> word){
    super(context, 0, word);

    this.actualdata = new ArrayList<WordFolder>();
    this.orignallist = new ArrayList<WordFolder>();
    actualdata.addAll(word); // 使用此方法设置您的视图
    orignallist.addAll(word);
}

public void filterData(String query){
    query = query.toLowerCase();

    actualdata.clear();
    if(query.isEmpty()){
        actualdata.addAll(orignallist);
    }
    else {
        ArrayList<WordFolder> newlist = new ArrayList<>();
        for(WordFolder gd: orignallist) {

            if ((gd.getTitle().contains(query))) {
                newlist.add(gd);
            }
        }

        if(newlist.size() > 0){

            actualdata.addAll(newlist);
        }
    }

    notifyDataSetChanged();
}

然后在您的主类中将 itemAdapter.getfilter() 更改为 itemAdapter.filterData("your query"),现在应该可以正常工作。

英文:

Use this in your adapter:

private ArrayList&lt;WordFolder&gt; actualdata = new ArrayList&lt;WordFolder&gt;();
private ArrayList&lt;WordFolder&gt; orignallist= new ArrayList&lt;&gt;();
WordAdapter(Context context, ArrayList&lt;WordFolder&gt; word){
super(context, 0, word);
this.actualdata=new ArrayList&lt;WordFolder&gt;();
this.orignallist=new ArrayList&lt;WordFolder&gt;();
actualdata.addAll(word);//use this to set up your view
orignallist.addAll(word);
}
public void filterData(String query){
query=query.toLowerCase();
actualdata.clear();
if(query.isEmpty()){
actualdata.addAll(orignallist);
}
else {
ArrayList&lt;WordFolder&gt; newlist = new ArrayList&lt;&gt;();
for(WordFolder gd: orignallist) {
if ((gd.getTitle().contains(query))  ) {
newlist.add(gd);
}
}
if(newlist.size()&gt; 0){
actualdata.addAll(newlist);
}
}
notifyDataSetChanged();
}

Then change in your mainclass itemAdapter.getfilter() to itemAdapter.filterData(&quot;your query&quot;)

Now it should work

huangapple
  • 本文由 发表于 2020年9月2日 16:33:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63701686.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定