当用户触摸屏幕上的任意位置时,如何一一填充Recycler视图?

时间:2019-06-04 14:14:29

标签: java android

我想在用户单击屏幕上任意位置时填充recyclerview项。例如,在第一触摸上加载第一项在第二触摸上加载第二项在第三触摸上加载第三项,依此类推。我不知道该如何实现。

这是我的适配器代码

适配器

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder>{

        List<MessageModel> list;
        Context context;

        public MessageAdapter(List<MessageModel> list, Context context) {
            this.list = list;
            this.context = context;
        }

        @NonNull
        @Override
        public MessageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
           View view = LayoutInflater.from(context)
                   .inflate(R.layout.chatbubble, viewGroup, false);
           ViewHolder myHolder = new ViewHolder(view);

            return myHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull MessageAdapter.ViewHolder viewHolder, int i) {
            MessageModel model = list.get(i);
            if(model.getSender().equals("left")){
                viewHolder.left.setText(model.getText());
                viewHolder.right.setVisibility(View.GONE);
                viewHolder.middle.setVisibility(View.GONE);
            } else if(model.getSender().equals("right")){
                viewHolder.right.setText(model.getText());
                viewHolder.middle.setVisibility(View.GONE);
                viewHolder.left.setVisibility(View.GONE);
            } else {
                viewHolder.middle.setText(model.getText());
                viewHolder.left.setVisibility(View.GONE);
                viewHolder.right.setVisibility(View.GONE);
            }
        }

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

        public class ViewHolder extends RecyclerView.ViewHolder {

            TextView left, right, middle;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);

                left = itemView.findViewById(R.id.message_incoming);
                right = itemView.findViewById(R.id.message_outgoing);
                middle = itemView.findViewById(R.id.message_middle);

            }
        }
    }

1 个答案:

答案 0 :(得分:0)

在保存您的Activity的{​​{1}}中,进行以下代码更改。

  1. RecyclerViewonClickListener添加到onTouchListener中。

    RecyclerViewrecyclerView.setOnClickListener()

  2. 添加代码以将这些项目添加到上述事件侦听器中的recyclerView.setOnTouchListener()中。

    yourList.add(“您的商品”);
    adapter.notifyItemInserted(int positionAtWhichItemWasInserted);

    adapter.notifyDatasetChanged();

    //由于某种原因,我无法格式化上面的代码片段。

  3. 在将项目添加到RecyclerView列表后,请确保调用RecyclerViewnotifyItemInserted()