android:使用RecyclerView.Adapter将项目添加到现有列表后的排序列表

时间:2016-09-22 09:53:38

标签: android android-recyclerview recycler-adapter

我有一个RecyclerView,它显示按降序排序的项目列表,在我最初启动屏幕时工作正常,但是当我向现有列表中添加更多项目并使用notifyDataSetChanged()方法将其设置为适配器时list按升序排序,新项目添加到视图的底部。

下面是适配器

 public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.ViewHolder> {
    private List<Cinema> lists;
    private int savedItems;

    public RecycleAdapter(List<Cinema> cinemas, int savedItems) {
        this.lists = cinemas;
        this.savedItems = savedItems;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView cinemaTitle;
        public TextView cinemaDescription;
        public TextView cinemaDate;
        public LinearLayout newLayout;

        public ViewHolder(View view) {
            super(view);
            cinemaTitle = (TextView) view.findViewById(R.id.cinema_title);
            cinemaDescription = (TextView) view.findViewById(R.id.description_text);
            cinemaDate = (TextView) view.findViewById(R.id.cinema_date);
            newLayout = (LinearLayout) view.findViewById(R.id.new_cinema_layout);
        }
    }

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

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Cinema cinema = cinemas.get(position);
        if (cinema.getId() > savedItems) {
            holder.newLayout.setVisibility(View.VISIBLE);
        } else {
            holder.newLayout.setVisibility(View.INVISIBLE);
        }

        String title = cinema.getMessage().trim();
        String description = cinema.getDescription().trim();
        String date = cinema.getPublishedDate().trim();
        holder.cinemaTitle.setText(title);
        holder.cinemaDescription.setText(description);
        holder.cinemaDate.setText(date);
    }

    public void setCineams(List<Cinema> cinemas) {
        this.cinemas = cinemas;
        notifyDataSetChanged();
    }

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

以及从Fragment更新列表的方法如下:

    @Override
    public void onCinemaUpdated() {
    cinemas = firebaseHelper.getAllCinemas();
    //Method which sorts the lists in descending order after adding new items into it
    sortCinemas();
    if (recycleAdapterAdapter != null) {
        recycleAdapterAdapter.setCineams(cinemas);
    }
}

我不知道为什么会出现这种行为。有人可以澄清这个吗?

1 个答案:

答案 0 :(得分:0)

将构造函数和setCinemas方法代码更改为:让我知道它是否有帮助..

public RecycleAdapter(List<Cinema> cinemas, int savedItems) {
        this.lists = cinemas;
        this.savedItems = savedItems;
    }

public void setCineams(List<Cinema> cinemas) {
        this.lists = cinemas;
        notifyDataSetChanged();
    }