我有一个RecyclerView,当我点击第一个视图时,它会添加另一个视图,就像在图像中一样,我想要的是设置"添加"查看哪个ID是" 1"固定在回收器的最后位置而不是第一个位置。
我的适配器:
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);
}
}
}
在活动中:
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("");
答案 0 :(得分:0)
您尝试过类似的事情吗?
public void addItem(String name) {
if (items.size() != 0) {
removeItem(items.size() - 1);
items.add(name);
items.add("Add");
} else
items.add("Add");
notifyItemInserted(items.size() - 1);
}
然后添加项目的ID为items.size() -1
修改强> 使用以下代码更改您的Holder课程:
if(position == items.size() - 1)
{
holder.theLayout.setBackgroundColor(Color.parseColor("#7F9099"));
holder.eventName.setText("Add");
}
答案 1 :(得分:0)
我通过创建一个允许页脚和标题的自定义适配器来解决它,这是GitHub中的项目:https://github.com/u3breeze/android-RecyclerView-WithHeaderAndFooter