问题
How can I limit the number of items displayed by the RecyclerView ?
I can limit the amount inserted it if I override getChildCount
, but that causes it to only insert that number and then stop. I want it to keep inserting/scrolling, but only display X number of items.
(Note: The height of each item can differ, so it's important that the limit is based on quantity rather than some hard coded value.)
回答1:
Inside your Recyclerview's adapter class;
private final int limit = 10;
@Override
public int getItemCount() {
if(ad_list.size() > limit){
return limit;
}
else
{
return ad_list.size();
}
}
回答2:
You can simply override getCount()
method and test if adapter data array is superior than "DESIRED_MAX" then return "DESIRED_MAX" else just return the data array length or size (array/ArrayList)
回答3:
One solution is to set width of each child programmatically,
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.MY_ITEM_TO_INFALTE, parent, false);
itemView.getLayoutParams().width = (int) (getScreenWidth() / NUMBERS_OF_ITEM_TO_DISPLAY); /// THIS LINE WILL DIVIDE OUR VIEW INTO NUMBERS OF PARTS
return new MyCreationItemAdapter.MyViewHolder(itemView);
}
public int getScreenWidth() {
WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.x;
}
回答4:
if you want it to keep inserting/scrolling, but only display X number of items, then I have a solution: setVisibility
to VISIBLE for X items, and other is GONE.
public static final class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View view) {
super(view);
handleShowView(view);
}
private void handleShowView(View view) {
if (getAdapterPosition() > X - 1) {
view.setVisibility(View.GONE);
return;
}
view.setVisibility(View.VISIBLE);
}
}
hope this helps
来源:https://stackoverflow.com/questions/50867570/how-to-limit-number-of-items-in-recyclerview