I have a RecyclerView, when I click in the first view it adds another view like in the image, what I want is to set the “add” view which ID is “1” to be fixed in the last position of the recycler instead in the first.
My adapter:
public class AddEventsAdapter extends RecyclerView.Adapter<AddEventsAdapter.ViewHolder> { private List<String> items = new ArrayList<>(); public void addItem(String name) { items.add(name); notifyItemInserted(items.size() - 1); } 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.setEventNameName(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); theLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (getAdapterPosition()>0){ removeItem(getAdapterPosition()); }else { addItem(""); } } }); } public void setEventNameName(String TheEventName){ eventName.setText(TheEventName); } } }
In the activity:
final AddEventsAdapter AddContainer = new AddEventsAdapter(); AddEventsRecycler.setLayoutManager(new LinearLayoutManager(this)); AddEventsRecycler.setAdapter(AddContainer); AddEventsRecycler.setItemViewCacheSize(666); RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator(); itemAnimator.setAddDuration(1000); itemAnimator.setRemoveDuration(1000); AddEventsRecycler.setItemAnimator(itemAnimator); AddContainer.addItem("");
Advertisement
Answer
I solved it by creating a custom adapter that allows a footer and a header, here is the project in GitHub: https://github.com/u3breeze/android-RecyclerView-WithHeaderAndFooter