朋友,我有一个片段,其中包含搜索视图和recyclerview。我想在recyclerview数据上实现该搜索视图。当我尝试从片段中的适配器类中调用方法时,我遇到了问题,它不允许它并要求我将适配器类中的方法设置为静态,这是不好。这是必需的片段代码-
private void processQuery(String query) {
// in real app you'd have it instantiated just once
ArrayList<String> result = new ArrayList<>();
// case insensitive search
for (String category : category_name) {
if (category.toLowerCase().contains(query.toLowerCase())) {
result.add(category);
}
}
(MyCategoryAdaptercheckbox) MyAdapter.setCategorynames(result);
}
我在这条线上出现错误-
(MyCategoryAdaptercheckbox) MyAdapter.setCategorynames(result);
这是我的MyAdaper声明和初始化-
RecyclerView.Adapter MyAdapter;
MyAdapter = new MyCategoryAdaptercheckbox(getMyCategoryAdapter1, getActivity().getApplicationContext(),category_name);
recyclerView.setAdapter(MyAdapter);
这是我的适配器类(setCategorynames)方法,要求我将此方法设置为静态-
public void setCategorynames(List<String> category_name) {
this.category_name = category_name;
notifyDataSetChanged();
}
所以我想知道如何在片段中调用适配器类的方法? 我的适配器类代码-
public class MyCategoryAdaptercheckbox extends RecyclerView.Adapter<MyCategoryAdaptercheckbox.ViewHolder> {
List<GetMyCategoryAdapter> getMyCategoryAdapter;
Context context;
List<String> category_name;
GetMyCategoryAdapter getMyCategoryAdapter1;
public MyCategoryAdaptercheckbox(List<GetMyCategoryAdapter> getMyCategoryAdapter, Context context, List<String> category_name) {
this.getMyCategoryAdapter = getMyCategoryAdapter;
this.context = context;
this.category_name = category_name;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
if (viewHolder instanceof ViewHolder){
}
getMyCategoryAdapter1 = getMyCategoryAdapter.get(i);
((ViewHolder) viewHolder).tv_categorytitle.setText(getMyCategoryAdapter1.getC_name());
((ViewHolder) viewHolder).tv_categoryid.setText(getMyCategoryAdapter1.getC_id());
((ViewHolder) viewHolder).gt= getMyCategoryAdapter1;
}
public void filterList(ArrayList<String> filterdNames) {
this.category_name = filterdNames;
notifyDataSetChanged();
}
}
}
答案 0 :(得分:0)
我在您的代码中看到的一个问题是*traser
,因为setCategorynames(List<String> category_name) method is not resolved
没有转换为MyAdapter
您需要替换
(MyCategoryAdaptercheckbox)
通过
(MyCategoryAdaptercheckbox) MyAdapter.setCategorynames(result);
答案 1 :(得分:0)
首先创建一个这样的接口;
public interface ProcessQueryListener{
void onSuccess(List<String> result);
}
在适配器中,您应该根据需要实现此侦听器。基本上就是这样:
public MyCategoryAdaptercheckbox extends RecyclerView.Adapter implements ProcessQueryListener {
@Override
public void onSuccess(List<String> result){
this.setCategorynames(result);
}
}
.
.
在片段的processQuery函数中,应调用此ProcessQueryListener。例如;
ProcessQueryListener queryListener = (MyCategoryAdaptercheckbox) MyAdapter;
private void processQuery(String query) {
// in real app you'd have it instantiated just once
ArrayList<String> result = new ArrayList<>();
// case insensitive search
for (String category : category_name) {
if (category.toLowerCase().contains(query.toLowerCase())) {
result.add(category);
}
}
if (queryListener != null) {
queryListener.onSuccess(result);
}
}