搜索不在“RecyclerView”

时间:2018-04-20 13:41:04

标签: android

我正在尝试使用recyclerview部分中的工具搜索功能 它没有工作但也没有显示错误...

我尝试使用edittext addTextChangedListener方法。 然后在adapter添加notifydatachanged方法。 尝试正常recyclerview它的工作正常但是当使用部分recyclerview时它不起作用 抱歉英文不好

这里是mainActivty 这里我从服务器获取数据并传递给此类中的适配器我添加了filter recyclerview的方法

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

    init();

    initView();
    setUpRecyclerView();
    tempModels = new ArrayList<TempModel>();
    serviceRequest();
    searchItem();
  }

  private void init() {

    mAdapter = new ItemRecyclerViewAdapter(SectionRvSearchPrac.this);
  }

  private void initView() {

    mEt_search = findViewById(R.id.et_search_main);
  }

  ///////////////////////////////

  private void searchItem() {

    mEt_search.addTextChangedListener(
        new TextWatcher() {
          @Override
          public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

          @Override
          public void onTextChanged(CharSequence s, int start, int before, int count) {}

          @Override
          public void afterTextChanged(Editable s) {
            filter(s.toString());
          }
        });
  }


  //method for filter list is here..


  private void filter(String text) {
    ArrayList<TempModel> mFilter_list = new ArrayList<>();

    for (TempModel tempModel : tempModels) {

      if (tempModel.getName().toLowerCase().contains(text.toLowerCase())) {
        mFilter_list.add(tempModel);
      }
    }
    Log.d(TAG, "filter: " + mFilter_list);
    mAdapter.filterList(mFilter_list);
  }

  //////////////////
  private void setUpRecyclerView() {
    recyclerView = (RecyclerView) findViewById(R.id.sectioned_recycler_view);
    recyclerView.setHasFixedSize(true);
    linearLayoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(linearLayoutManager);
  }

  private void serviceRequest() {

    StringRequest stringRequest =
        new StringRequest(
            Request.Method.GET,
            JSON_URL,
            new Response.Listener<String>() {
              @Override
              public void onResponse(String response) {
                parseJason(response);
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                // displaying the error in toast if occurrs
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT)
                    .show();
              }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);

    requestQueue.add(stringRequest);
  }

  public void parseJason(String response) {
    {
      Log.d(TAG, "onResponse: " + response);

      String[] first;
      ArrayList<String> sewction_list = new ArrayList<>();

      try {
        JSONObject jsonObject = new JSONObject(response);

        JSONArray jsonArray = jsonObject.getJSONArray("data");

        String data = jsonArray.getString(0);

        first = data.split(Pattern.quote("***^^^***"));

        myList_sec = new ArrayList<>(Arrays.asList(first));

        for (int j = 0; j < myList_sec.size(); j++) {

          myList_first =
              new ArrayList<>(Arrays.asList(myList_sec.get(j).split(Pattern.quote("^^^^"))));

          sewction_list.add(myList_first.get(0));
          myList_second =
              new ArrayList<>(Arrays.asList(myList_first.get(1).split(Pattern.quote("^^"))));

          ArrayList<String> id = new ArrayList<>();
          ArrayList<String> url = new ArrayList<>();
          ArrayList<String> img = new ArrayList<>();
          ArrayList<String> name = new ArrayList<>();
          for (int i = 0; i < myList_second.size(); i++) {

            myList_third =
                new ArrayList<>(Arrays.asList(myList_second.get(i).split(Pattern.quote("**"))));

            url.add(myList_third.get(0));
            img.add(myList_third.get(1));
            name.add(myList_third.get(2));
            id.add(myList_third.get(3));

            tempModels.add(
                new TempModel(
                    myList_third.get(2),
                    myList_third.get(0),
                    myList_third.get(1),
                    myList_third.get(3)));
          }

          sectionModelArrayList.add(new SectionModel(sewction_list, tempModels));
          SectionRecyclerViewAdapter adapter =
              new SectionRecyclerViewAdapter(
                  SectionRvSearchPrac.this, recyclerViewType, sectionModelArrayList);

          recyclerView.setAdapter(adapter);
        }
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
  }

这是子项的myitemadapter类

public class ItemRecyclerViewAdapter
    extends RecyclerView.Adapter<ItemRecyclerViewAdapter.ItemViewHolder> {

  private static final String TAG = "adapter";

  private Context context;

  ArrayList<TempModel> tempModels;


  public ItemRecyclerViewAdapter(Context context) {
    this.context = context;
  }

  public void setData(ArrayList<TempModel> data) {
    this.tempModels = data;
  }

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

  @Override
  public void onBindViewHolder(ItemViewHolder holder, final int position) {
    String path = tempModels.get(position).getImage();
    holder.itemLabel.setText(tempModels.get(position).getName());
    Picasso.get().load(path).into(holder.imageView);

    holder.cardView.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {}
        });
  }

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

  /// here method for update filter list

  public void filterList(ArrayList<TempModel> filterdNames) {
    this.tempModels = filterdNames;
    notifyDataSetChanged();
  }

  class ItemViewHolder extends RecyclerView.ViewHolder {
    private TextView itemLabel;
    ImageView imageView;
    CardView cardView;

    public ItemViewHolder(View itemView) {
      super(itemView);

      itemLabel = (TextView) itemView.findViewById(R.id.item_label);
      cardView = itemView.findViewById(R.id.cardview);
      imageView = itemView.findViewById(R.id.img);
    }
  }

部分项目的部分模型

public class SectionModel {

  private ArrayList<String> sectionLabel;
  private ArrayList<TempModel> tempModels;

  public SectionModel(ArrayList<String> sectionLabel, ArrayList<TempModel> tempModels) {
    this.sectionLabel = sectionLabel;
    this.tempModels = tempModels;
  }

  public ArrayList<String> getSectionLabel() {
    return sectionLabel;
  }

  public ArrayList<TempModel> getTempModels() {
    return tempModels;
  }
}

项目的模型类

public class TempModel implements Parcelable{
    String name;
    String url;
    String image;
    String num;

    public TempModel() {
    }

    public TempModel(String name, String url, String image, String num) {
        this.name = name;
        this.url = url;
        this.image = image;
        this.num = num;
    }

    protected TempModel(Parcel in) {
        name = in.readString();
        url = in.readString();
        image = in.readString();
        num = in.readString();
    }

    public static final Creator<TempModel> CREATOR = new Creator<TempModel>() {
        @Override
        public TempModel createFromParcel(Parcel in) {
            return new TempModel(in);
        }

        @Override
        public TempModel[] newArray(int size) {
            return new TempModel[size];
        }
    };

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getNum() {
        return num;
    }

    public void setNum(String num) {
        this.num = num;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeString(url);
        dest.writeString(image);
        dest.writeString(num);
    }
}

sectionadapter类

public class SectionRecyclerViewAdapter
    extends RecyclerView.Adapter<SectionRecyclerViewAdapter.SectionViewHolder> {

  private static final String TAG = "section";

  class SectionViewHolder extends RecyclerView.ViewHolder {
    private TextView sectionLabel, showAllButton;
    private RecyclerView itemRecyclerView;

    public SectionViewHolder(View itemView) {
      super(itemView);
      sectionLabel = (TextView) itemView.findViewById(R.id.section_label);
      itemRecyclerView = (RecyclerView) itemView.findViewById(R.id.item_recycler_view);
    }
  }

  private Context context;
  private RecyclerViewType recyclerViewType;
  private ArrayList<SectionModel> sectionModelArrayList;

  public SectionRecyclerViewAdapter(
      Context context,
      RecyclerViewType recyclerViewType,
      ArrayList<SectionModel> sectionModelArrayList) {
    this.context = context;
    this.recyclerViewType = recyclerViewType;
    this.sectionModelArrayList = sectionModelArrayList;
  }

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

  @Override
  public void onBindViewHolder(SectionViewHolder holder, int position) {
    final SectionModel sectionModel = sectionModelArrayList.get(position);
    holder.sectionLabel.setText(sectionModel.getSectionLabel().get(position));
    // recycler view for items
    holder.itemRecyclerView.setHasFixedSize(true);
    holder.itemRecyclerView.setNestedScrollingEnabled(false);
    GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 3);
    holder.itemRecyclerView.setLayoutManager(gridLayoutManager);

    /* set layout manager on basis of recyclerview enum type */

    ItemRecyclerViewAdapter adapter = new ItemRecyclerViewAdapter(context);
    adapter.setData(sectionModel.getTempModels());
    holder.itemRecyclerView.setAdapter(adapter);

  }

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

1 个答案:

答案 0 :(得分:1)

您的代码非常混乱,所以我只写我的解决方案。

public class SomeAdapter extends RecyclerView.Adapter<SomeAdapter.SomeViewHolder> implements Filterable{
...

@Override
public Filter getFilter() {
    Filter filter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence charSequence) {
            mMainList = mYourJSONResponseList;
            FilterResults results = new FilterResults();
            ArrayList<YourModel> mFilter_list = new ArrayList<>();
            //Place your logic
            for (YourModel model : mMainList) {
               if(model.getName().
                    toLowerCase().contains(text.toLowerCase())) {
                mFilter_list.add(model);
                }
            }
            results.count = mFilter_list.size();
            results.values = mFilter_list;
            return results;
        }

        @Override
        protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
            mMainList = (ArrayList<YourModel>) filterResults.values;
            notifyDataSetChanged();
        }
    };

    return filter;
}

并将其添加到文本侦听器

@Override
      public void afterTextChanged(Editable s) {

        //Add this
        adapter.getFilter().filter(s.toString())
      }

请注意!您将在RecyclerView中仅显示mMainList此列表,并检查nullpointerexceptions