当前位置: 首页 > 知识库问答 >
问题:

Android过滤器回收商查看来自改造的数据

洪河
2023-03-14

我有这个回收器视图,我从Retrofit API获取数据,问题是当我尝试在回收器中制作过滤器时,我在互联网上搜索,所有示例都是字符串列表,但我有对象列表,我如何解决这种情况并在工具栏中创建过滤器?我会发布我的代码,希望有人能帮忙,谢谢

活动

public class TodoList extends AppCompatActivity implements DialogFragUpdateListener {
    RecyclerView todoRecyclerView;
    private RecyclerView.Adapter todoAdapter;
    private RecyclerView.LayoutManager todoLayoutManager;
    public List<ToDo> results;
    public List<String> list = new ArrayList<>();


    TodoRecyclerAdapter recyclerAdapter;
    Context context;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_todo_list);


        todoRecyclerView = (RecyclerView)findViewById(R.id.todoRecyclerView);
        todoRecyclerView.setHasFixedSize(true);
        results= new ArrayList<ToDo>();


        todoLayoutManager = new LinearLayoutManager(this);
        todoRecyclerView.setLayoutManager(todoLayoutManager);

       
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TodoList.this,AddToDo.class);
                startActivity(intent);
            }
        });}

    public void getRetrofitObject() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        APIService service = retrofit.create(APIService.class);
        Call<Result> call = service.getresults();
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {

                results = response.body().getResults();
                if(recyclerAdapter == null){

                recyclerAdapter = new TodoRecyclerAdapter(this,results);
                todoRecyclerView.setAdapter(recyclerAdapter);
            }
            else{

                recyclerAdapter.setData(results);
                recyclerAdapter.notifyDataSetChanged();
            }

            }
            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                Log.d("onFailure", t.toString());
            }});}

    @Override
    public void OnDBUpdate() {


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        APIService service = retrofit.create(APIService.class);
        Call<Result> call = service.getresults();
        call.enqueue(new Callback<Result>() {
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                results = response.body().getResults();
                if(recyclerAdapter == null){

                recyclerAdapter = new TodoRecyclerAdapter(this,results);
                todoRecyclerView.setAdapter(recyclerAdapter);
            }
            else{

                recyclerAdapter.setData(results);
                recyclerAdapter.notifyDataSetChanged();
            }
            }
            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                Log.d("onFailure", t.toString());
            }});
    }




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

            @Override
            public void onFocusChange(View v, boolean hasFocus) {

            }
        });

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
recyclerAdapter.getFilter().filter(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String searchQuery) {
               
                return true;
            }
        });

        MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                return true;
            }
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                return true;
            }
        });
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_search) {

            return true;
        }
        return super.onOptionsItemSelected(item);
    }}

这是适配器

public class TodoRecyclerAdapter  extends RecyclerView.Adapter<TodoRecyclerAdapter.ViewHolder>  {
static List<ToDo> todoResults;
static Context context;
List<ToDo>results;
ArrayList<ToDo> arraylist;
private List<String> mDefaultCheeses;



public TodoRecyclerAdapter(Callback<Result> callback, List<ToDo> results) {
    this.todoResults = results;
    arraylist = new ArrayList<ToDo>();
    arraylist.addAll(todoResults);

}
@Override
public TodoRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.todo_items, null);
    ViewHolder viewHolder = new ViewHolder(itemLayoutView);
    return viewHolder;
}
@Override
public void onBindViewHolder(final TodoRecyclerAdapter.ViewHolder holder, final int position) {
    holder.todoTitle.setText(todoResults.get(position).getTODO_TITLE().toString());
    String priority = todoResults.get(position).getPriority().toString();
    if (priority.equals("Low")) {
        holder.todoImage.setImageResource(R.drawable.low);
    } else if (priority.equals("Normal")) {
        holder.todoImage.setImageResource(R.drawable.normal);
    } else if (priority.equals("High")) {
        holder.todoImage.setImageResource(R.drawable.high);
    }
}


@Override
public int getItemCount() {
    return  todoResults.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    public TextView todoTitle;
    public ImageView todoImage;
    public ViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        todoTitle = (TextView) itemLayoutView.findViewById(R.id.todo_title);
        todoImage = (ImageView) itemLayoutView.findViewById(R.id.imageView2);
    }}

这是菜单

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.android.nigeriaexams.ui.SettingsFragment">
<item android:id="@+id/action_search"
    android:title="Search"
    android:icon="@drawable/ic_search"
    app:showAsAction="collapseActionView|always"
    app:actionViewClass="android.support.v7.widget.SearchView"
    android:layout_width="wrap_content" />

共有3个答案

孟哲
2023-03-14

我已经尝试了下面的代码:我认为它会工作。

公共类SearchAdapter扩展RecyclerView.Adapter实现可过滤{

private ItemFilter itemFilter;
private ArrayList<CommonModel> arrayList;//filtered emoji collection
private ArrayList<CommonModel> fullList;//Full emoji collection
private Context context;

public SearchAdapter(final Context context, final ArrayList<CommonModel> arrayList) {
    this.arrayList = arrayList;
    this.fullList = arrayList;
    this.context = context;
    itemFilter = new ItemFilter();
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_search, parent, false);
    final ViewHolder viewHolder = new ViewHolder(view);
    return viewHolder;
}

@Override
public void onBindViewHolder(KeyboardEmojiSearchAdapter.ViewHolder holder, int position) {
    final CommonModel commonModel = arrayList.get(position);

    Glide.with(context).load(commonModel.getDisplayImage()).asBitmap().into(holder.iv);
}

@Override
public int getItemCount() {
    return arrayList.size();
}

@Override
public Filter getFilter() {
    return itemFilter;
}

/**
 * Holder class to hold grid item
 */
public static class ViewHolder extends RecyclerView.ViewHolder {
    private ImageView iv;


    public ViewHolder(View view) {
        super(view);
        iv = (ImageView) view.findViewById(R.id.row_search_iv);

    }
}

/**
 * Filter class allows filtering by tags from Emoji collection
 */
private class ItemFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {

        final FilterResults results = new FilterResults();
        final ArrayList<CommonModel> newFilteredList = new ArrayList<>();

        if (constraint.toString().trim().length() > 0) {

            final String filterString = constraint.toString().toLowerCase();
            final int count = fullList.size();

            for (int i = 0; i < count; i++) {
                for (int j = 0; j < fullList.get(i).getTagList().size(); j++) {
                    if (fullList.get(i).getTagList().get(j).toLowerCase().startsWith(filterString)) {
                        newFilteredList.add(fullList.get(i));
                        break;
                    }
                }
            }
        } else {
            newFilteredList.addAll(fullList);
        }

        results.values = newFilteredList;
        results.count = newFilteredList.size();

        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        arrayList = (ArrayList<CommonModel>) results.values;
        notifyDataSetChanged();
    }
}

请参考下面的代码。

EDT search . addtextchangedlistener(new text watcher(){ @ Override public void before text changed(char sequence char sequence,int i,int i1,int i2) { }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            gridAdapter.getFilter().filter(charSequence);
        }

        @Override
        public void afterTextChanged(Editable editable) {
        }
    });
景帅
2023-03-14

您可以在适配器中实现可过滤接口,并且可以这样做

public class TodoRecyclerAdapter extends RecyclerView.Adapter<TodoRecyclerAdapter.ViewHolder> implements Filterable {

        static List<ToDo> todoResults;
        static Context context;
        List<ToDo>results;
        ArrayList<ToDo> arraylist;
        private List<String> mDefaultCheeses;

        private ToDoListFilter listFilter;

        private List<ToDo> mData;
        private List<ToDo> originalData;


        public TodoRecyclerAdapter(Callback<Result> callback, List<ToDo> results) {
            this.todoResults = results;
            arraylist = new ArrayList<ToDo>();
            arraylist.addAll(todoResults);

        }

        public List<ChatListData> getData() {
            return mData;
        }

        public void setData(List<ChatListData> mData) {
            this.mData = mData;

            if (originalData == null) {
                originalData = mData;
            }
        }

        @Override
        public TodoRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.todo_items, null);
            ViewHolder viewHolder = new ViewHolder(itemLayoutView);
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final TodoRecyclerAdapter.ViewHolder holder, final int position) {
            holder.todoTitle.setText(todoResults.get(position).getTODO_TITLE().toString());
            String priority = todoResults.get(position).getPriority().toString();
            if (priority.equals("Low")) {
                holder.todoImage.setImageResource(R.drawable.low);
            } else if (priority.equals("Normal")) {
                holder.todoImage.setImageResource(R.drawable.normal);
            } else if (priority.equals("High")) {
                holder.todoImage.setImageResource(R.drawable.high);
            }
        }

         @Override
            public Filter getFilter() {
                if (listFilter == null)
                    listFilter = new ToDoListFilter(this,originalData);

                return listFilter;
            }

        @Override
        public int getItemCount() {
            return  todoResults.size();
        }

        public static class ViewHolder extends RecyclerView.ViewHolder {
            public TextView todoTitle;
            public ImageView todoImage;
            public ViewHolder(View itemLayoutView) {
                super(itemLayoutView);
                todoTitle = (TextView) itemLayoutView.findViewById(R.id.todo_title);
                todoImage = (ImageView) itemLayoutView.findViewById(R.id.imageView2);
            }
        }


        private class ToDoListFilter extends Filter {

            private final TodoRecyclerAdapter listAdapter;

            private final List<ToDo> originalData;
            private List<ToDo> filteredData;

            public ToDoListFilter(TodoRecyclerAdapter listAdapter, List<ToDo> originalData) {
                this.listAdapter = listAdapter;
                this.originalData = originalData;
                this.filteredData = new ArrayList<>();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                filteredData.clear();
                final FilterResults results = new FilterResults();

                Log.d("performFiltering: " , constraint.toString());

                if (TextUtils.isEmpty(constraint.toString())) {
                    filteredData.addAll(originalData);
                } else {
                    final String filterPattern = constraint.toString().toLowerCase().trim();

                    for (final ToDo user : originalData) {
                        // set condition for filter here
                        if (user.getToUserName().toLowerCase().contains(filterPattern)) {
                            filteredData.add(user);
                        }
                    }
                }

                results.values = filteredData;
                results.count = filteredData.size();
                return results;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {

                //listAdapter.getData().clear();
                listAdapter.setData((List<ToDo>) filterResults.values);
                listAdapter.notifyDataSetChanged();

            }
        }
    }

把这个叫做

listAdapter.getFilter().filter(query);

有关更多信息,请查看此处

希望它能解决你的问题。。。

司马辉
2023-03-14

向自定义适配器添加filter()方法。

private ArrayList<ToDo> arraylist = null, toDoArrayList;

public TodoRecyclerAdapter(Callback<Result> callback, List<ToDo> results) {
    this.todoResults = results;
    arraylist = new ArrayList<ToDo>();
    arraylist.addAll(todoResults);
    this.toDoArrayList = new ArrayList<ToDo>();
    this.toDoArrayList.addAll(objects);
}

public void filter(String filterString) {
    filterString = filterString.toLowerCase(Locale.getDefault());
    arraylist.clear();
    if (filterString.length() == 0) {
        arraylist.addAll(toDoArrayList);
    }
    else {
        for (ToDo toDO : toDoArrayList) {
            if(toDO.getYourSearchValue().toLowerCase(Locale.getDefault()).contains(filterString)) {
                arraylist.add(toDO);
            }
        }
    }
    notifyDataSetChanged();
}

 类似资料:
  • 我使用此解决方案来过滤我的。使用该解决方案,我能够在键入时获得结果。但是当我清除搜索小部件时,我没有得到完整的列表,而是得到了空的。 这就是我的结果。https://imgur.com/nwyetEd 这是我的 这是我的 这是我使用过滤器的< code >活动 有人能帮助我吗?

  • 我使用SearchView过滤我的应用程序的RecyclerView,就像这篇文章中描述的一样: 如何使用SearchView筛选RecyclerView 一开始一切看起来都很好,我可以根据需要过滤RecyclerView,但是经过一些尝试,出现了两个问题: 如果我在SearchView中输入文本太快,应用程序会崩溃,并出现以下日志: E/AndroidRuntime: FATAL EXCEPTI

  • 我正试图在我的RecyclerView中实现搜索过滤器,就像在这篇文章中一样 我已经对它进行了调试,它确实按照预期过滤了项目,但列表在应用程序中似乎没有改变。一、 E:我过滤一个名字,有7个结果,在屏幕上是原始列表。 我的 onCreateMenu活动选项是: 我的适配器如下所示: 我忘了什么? 提前致谢!

  • 我有一个关于我的活动的。当用户单击项目时,我想显示我的自定义对话框并将回收视图项目数据显示到对话框中,recylerview工作正常,但问题是当我单击该项目时,该应用程序不幸停止了一些错误 这是我的日志 进程:index=-1 at java.util.ArrayList.get(数组列表.java:310) 在 android.os.处理程序.处理程序.java.java:95) 在.java.

  • 假设我单击2位置的项目(记住其布局是颠倒的),然后调用 通知项目已更改(2[位置]) 在onBindViewHolder中,我在单击的项目上显示一些视图,因此它的高度会发生变化,当RecyclView测量它的孩子时,它会意识到它应该移动一些项目以使该项目的高度变化看起来引人入胜))。DefaultItemAnimator会处理它,但它会将所有低于“U are??? Omg谢谢u”项目的孩子向下移动

  • 当试图从API获取JSON数据并在RecyclerView上显示时,我得到以下错误: 我已经使用RecyclerView有时,我从来没有这个问题。 主要活动: 适配器: 取景框: 我搜索了很多如何解决这个错误,但我不能。