我只能在Recyclerview中设置来自API的四个数据。 API中的数据是动态的。如果有4个以上的数据,则最后一个应隐藏起来,而最近的数据应显示在顶部。我已经研究过,但找不到适用的解决方案。
我的Adpater
public class EventRecyclerAdapter extends RecyclerView.Adapter<EventRecyclerAdapter.MyViewHolder> {
Context context;
private ArrayList<String> start;
private AdapterView.OnItemClickListener listener;
private ArrayList<String> desc;
private ArrayList<EventData>data;
public EventRecyclerAdapter(Context context, ArrayList<EventData> data) {
this.context = context;
this.data = data;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.content_events, parent, false);
return new EventRecyclerAdapter.MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(EventRecyclerAdapter.MyViewHolder holder, int position) {
holder.start.setText(data.get(position).getStartDate());
holder.des.setText(Html.fromHtml(data.get(position).getName()));
}
@Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView start, des, viewall,name;
private CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
start = (TextView) itemView.findViewById(R.id.startdate);
des = (TextView) itemView.findViewById(R.id.description);
viewall = (TextView) itemView.findViewById(R.id.viewall);
}
}
}
我将数据设置如下
private void initEventRecycler() {
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
eventR.setLayoutManager(mLayoutManager);
eventR.setItemAnimator(new DefaultItemAnimator());
eventR.setNestedScrollingEnabled(false);
eventRecyclerAdapter = new EventRecyclerAdapter(MainActivity.this, events);
eventR.setAdapter(eventRecyclerAdapter);
}
答案 0 :(得分:3)
如果您在数组列表中缺少数据,那么您将进入适配器,然后使用此代码仅显示5个项目。
@Override
public int getItemCount() {
if (data!= null && data.size() < 5) {
return data.size();
} else {
return 5;
}
}
如果您有随机排列的数据列表,请先将其从最新到旧短,然后发送到适配器。
希望它对您有用。
答案 1 :(得分:0)
EventData[] mData = new EventData[4];
int writeIndex = 0;
public void add(Object o) {
ring[writeIndex % ring.length] = o;
writeIndex++;
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mData.lenght;
}
ArrayCircularQueue.java