Java – Android: reverse the position of recyclerview
•
Java
I'm setting up a recyclerview like a list. I want to have a button at the bottom of the list to add more views when clicking. I think the easier way is to take position 0 as the first one at the bottom and increase the position to the top, so I can add views when clicking the view in position 0
This is my adapter:
public class AddEventsAdapter extends RecyclerView.Adapter<AddEventsAdapter.ViewHolder> { public List<String> items = new ArrayList<>(); public void addItem(String name) { notifyItemInserted(items.size() - 1); items.add(name); } public void removeItem(int position) { items.remove(position); notifyItemRemoved(position); notifyItemRangeChanged(position,items.size()); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.add_event_item,parent,false); return new ViewHolder(view); } @Override public int getItemCount() { return items.size(); } @Override public void onBindViewHolder(ViewHolder holder,int position) { holder.setData(position); holder.eventName.setText(i + ""); if(position == 0) { holder.theLayout.setBackgroundColor(Color.parseColor("#7F9099")); holder.eventName.setText("Add"); } } static int i; class ViewHolder extends RecyclerView.ViewHolder{ public TextView eventName; public RelativeLayout theLayout; public ViewHolder(final View itemView) { super(itemView); eventName = (TextView)itemView.findViewById(R.id.eventName); theLayout = (RelativeLayout)itemView.findViewById(R.id.backgroundevent); theLayout.setId(++i); } public void setData(final int position) { theLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (position == items.size() - 1) { addItem(""); } else { removeItem(position); } } }); } } }
You may notice some errors. I have completed this error in the past 10 hours, and I have encountered a logic failure
Solution
It solves the layoutmanager problem through the line addind setReverseLayout(true);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码