NotifyDataSetChanged函数不适用于我的recyclerview

时间:2018-01-18 11:55:45

标签: android android-recyclerview recycler-adapter notifydatasetchanged

我想通过searchview过滤一个recyclerview,但我在适配器的notifyDataSetChanged上遇到了问题。

在我的片段中,我将适配器设置在OnCreateView

中的recyclerview上
mAdapter = new EventsAdapter(getContext(), events);
eventRecyclerView.setAdapter(mAdapter);

然后我通过firebase填充我的recyclerview,然后调用

mAdapter.notifyDataSetChanged();

更新recyclerview

好的,列表显示正确。

我在searchview上调用OnQueryTextChange

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            //Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            Toast.makeText(getContext(), "ciao", Toast.LENGTH_LONG).show();
            String query = s.toLowerCase();
            newList.clear();
            for(Event event: events){
                String name = event.getEventName().toLowerCase();
                if(name.contains(query)){
                    newList.add(event);
                }
            }
            mAdapter.setFilter(newList);
            return true;
        }
    });

并且适配器中的函数setFilter

public void setFilter(List<Event> filteredwordlist) {
    oldList.clear();
    oldList.addAll(filteredwordlist);
    notifyDataSetChanged();
}

问题是没有发生,recyclerview不会更新

为什么?!?

谢谢大家的回答

修改

EventsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.fragment_events, container, false);
    Toolbar toolbar = (Toolbar) v.findViewById(R.id.toolbar);
    ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
    getComponent();
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    eventRecyclerView.setLayoutManager(layoutManager);
    eventRecyclerView.setHasFixedSize(true);

    eventRecyclerView.setOnScrollListener(new HidingScrollListener() {
        @Override
        public void onHide() {
            hideViews();
        }
        @Override
        public void onShow() {
            showViews();
        }
    });

    /*Event e1 = new Event("la figa", "EventoPosto1", "Indirizzo", "mal", "21/01/12", "asaSAsas", "ASSAS", "CIAOCIA");
    Event e2 = new Event("ciao", "EventoPosto1", "Indirizzo", "mal", "21/01/12", "asaSAsas", "ASSAS", "CIAOCIA");
    Event e3 = new Event("la vacca", "EventoPosto1", "Indirizzo", "mal", "21/01/12", "asaSAsas", "ASSAS", "CIAOCIA");



    events.add(e1);
    events.add(e2);
    events.add(e3);*/ //TODO ESCLUSO PROBLEMA FIREBASE

    mAdapter = new EventsAdapter(getContext(), events);
    eventRecyclerView.setAdapter(mAdapter);

    firebaseFirestore.collection("events").orderBy("time").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {//todo .limit(numero limite)
        @Override
        public void onComplete(Task<QuerySnapshot> task) {
            if(task.isSuccessful()){
                List<DocumentSnapshot> temp = task.getResult().getDocuments();
                for(int i = 0; i < temp.size(); i++){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ITALY);
                    SimpleDateFormat output = new SimpleDateFormat("dd\nMMMM", Locale.ITALY);
                    Date d = null;
                    try {
                        d = sdf.parse(temp.get(i).get("time").toString());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    String formattedTime = output.format(d);
                    events.add(new Event(temp.get(i).get("event_name").toString(),
                            temp.get(i).get("event_place").toString(),
                            temp.get(i).get("place").toString(),
                            temp.get(i).get("location").toString(),
                            formattedTime,
                            temp.get(i).get("small_pic").toString(),
                            temp.get(i).get("cover_pic").toString(),
                            temp.get(i).get("description").toString()));
                }
                mAdapter.notifyDataSetChanged();
            }
        }
    });

    return v;
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_events_toolbar, menu);

    SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
    searchView = (SearchView) menu.findItem(R.id.search)
            .getActionView();
    searchView.setSearchableInfo(searchManager
            .getSearchableInfo(getActivity().getComponentName()));
    searchView.setMaxWidth(Integer.MAX_VALUE);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            //mAdapter.getFilter().filter(s);
            String query = s.toLowerCase();
            newList.clear();
            for(Event event: events){
                String name = event.getEventName().toLowerCase();
                if(name.contains(query)){
                    newList.add(event);
                }
            }
            mAdapter.setFilter(newList);
            return true;
        }
    });

    super.onCreateOptionsMenu(menu, inflater);
}

EventsAdapter.java

public class EventsAdapter extends RecyclerView.Adapter<EventsAdapter.EventsViewHolder>{
private List<Event> mEvents = new ArrayList<>();
private List<Event> eventListFiltered = new ArrayList<>();
private Context mContext;
private View v;
private ImageView placeBack, nameDateBack;
private TextView eventNameEditText, eventLocationEditText, eventDateEditText;
private ImageView eventImageView;
private List<Event> filteredList = new ArrayList<>();
private List<Event> oldList = new ArrayList<>();

public EventsAdapter(Context context, ArrayList<Event> events) {
    mContext = context;
    mEvents = events;
    oldList = events;
    eventListFiltered = events;
}

@Override
public EventsAdapter.EventsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    v = LayoutInflater.from(parent.getContext()).inflate(R.layout.cell_event, parent, false);
    return new EventsViewHolder(v);
}

@Override
public void onBindViewHolder(EventsAdapter.EventsViewHolder holder, int position) {
    holder.bindEvents(eventListFiltered.get(position));
}

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

public class EventsViewHolder extends RecyclerView.ViewHolder {

    public EventsViewHolder(View itemView) {
        super(itemView);
        placeBack = (ImageView) itemView.findViewById(R.id.place_back);
        nameDateBack = (ImageView) itemView.findViewById(R.id.name_data_back);
        eventNameEditText = (TextView) itemView.findViewById(R.id.name_event);
        eventLocationEditText = (TextView) itemView.findViewById(R.id.place_event);
        eventDateEditText = (TextView) itemView.findViewById(R.id.date_event);
        eventImageView = (ImageView) itemView.findViewById(R.id.event_background);
        mContext = itemView.getContext();
    }

    public void bindEvents(Event event) {
        eventNameEditText.setText(event.getEventName());
        eventLocationEditText.setText(event.getEventPlace());
        eventDateEditText.setText(event.getEventDate());
        Picasso.with(mContext).load(event.getEventCover()).placeholder(R.mipmap.ic_launcher_round).error(R.mipmap.ic_launcher_round)
                .into(eventImageView, new Callback() {
                    @Override
                    public void onSuccess() {
                    }

                    @Override
                    public void onError() {

                    }
                });
    }
}





public void setFilter(List<Event> filteredwordlist) {
    filteredList.clear();
    filteredList.addAll(filteredwordlist);
    notifyDataSetChanged();
}

}

2 个答案:

答案 0 :(得分:0)

也许试试这个:

 public boolean onQueryTextChange(String s) {
        Toast.makeText(getContext(), "ciao", Toast.LENGTH_LONG).show();
        String query = s.toLowerCase();
        newList.clear();
        for(Event event: events){
            String name = event.getEventName().toLowerCase();
            if(name.contains(query)){
                newList.add(event);
            }
        }
        mAdapter.setFilter(newList);
        mAdapter.notifyDataSetChanged();
        return true;
    }

 public void setFilter(List<Event> filteredwordlist) {
    oldList.clear();
    oldList.addAll(filteredwordlist);

 }

答案 1 :(得分:-1)

在方法setFilter()中,调用notifyDatasetchanged(),如

mAdapter.notifyDatasetChanged();

这必须在您的活动或片段中完成,但不能在适配器中完成

public void setFilter(List<Event> filteredwordlist) {
    oldList.clear();
    oldList.addAll(filteredwordlist);
    mAdapter.notifyDataSetChanged();
}