How to Limit Number of Items in RecyclerView?

2020-07-08 06:34发布

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.)

4条回答
该账号已被封号
2楼-- · 2020-07-08 06:45

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楼-- · 2020-07-08 06:48

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

查看更多
家丑人穷心不美
4楼-- · 2020-07-08 07:00

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();
    }

}
查看更多
成全新的幸福
5楼-- · 2020-07-08 07:06

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;
    }
查看更多
登录 后发表回答