findLastVisibleItemPosition()返回-1

时间:2018-03-22 09:47:52

标签: android android-recyclerview pagination recyclerview-layout

创建适配器对象,找到recycleler view id以设置适配器,然后设置布局管理器。在滚动侦听器中,无法获得正确的LastVisibleItemPosition,它会向我返回-1findFirstVisibleItemPosition()也返回-1

    //Here is Adapter

public class CategoryProduct extends RecyclerView.Adapter<RecyclerView.ViewHolder> 
    `enter code here`{
        private static final int ITEM = 0;
        private static final int LOADING = 1;
        public String vertical = "";
        Context context;
        private boolean isLoadingAdded = false;
        private boolean retryPageLoad = false;
        private List<com.example.it.camanagement.model.CategoryProduct> dataSet;

        public CategoryProduct(ArrayList<com.example.it.camanagement.model.CategoryProduct> data, Context context, String vertical) {
            this.dataSet = data;

            this.context = context;
            this.vertical = vertical;

        }


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                          int viewType) {
            RecyclerView.ViewHolder viewHolder = null;
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            switch (viewType) {
                case ITEM:
                    View viewLoading;
                    if (vertical.equals("vertical")) {
                        viewLoading = LayoutInflater.from(parent.getContext())
                                .inflate(R.layout.category_product_list, parent, false);
                    } else {
                        viewLoading = LayoutInflater.from(parent.getContext())
                                .inflate(R.layout.category_product_list_grid, parent, false);
                    }
                    viewHolder = new MyViewHolder(viewLoading);
                    break;
                case LOADING:
                    View viewLoading1 = inflater.inflate(R.layout.item_progress, parent, false);
                    viewHolder = new LoadingVH(viewLoading1);
                    break;
            }
            return viewHolder;

        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, final int listPosition) {
            if (listPosition == dataSet.size() - 1) {
                CategoryDetails categoryDetails = (CategoryDetails) context;
                categoryDetails.onBottomReached(listPosition);
            }
            switch (getItemViewType(listPosition)) {

                case ITEM:
                    final MyViewHolder myViewHolder = (MyViewHolder) holder;
                    TextView textViewName = myViewHolder.productName;
                    // TextView textViewVersion = holder.textViewVersion;
                    ImageView imageView = myViewHolder.productImage;
                    RatingBar productRating = myViewHolder.productRasting;
                    TextView productCost = myViewHolder.productCost;
                    TextView productDiscount = myViewHolder.productDistCount;
                    TextView productCOLOR = myViewHolder.productColor;
                    TextView productId = myViewHolder.product_id;
                    TextView productModel = myViewHolder.productModel;
                    TextView productQuantity = myViewHolder.productQuantity;
                    productModel.setText(dataSet.get(listPosition).getModel());
                    productQuantity.setText(dataSet.get(listPosition).getQuantity());
                    productId.setText(dataSet.get(listPosition).getProduct_id());
                    textViewName.setText(dataSet.get(listPosition).getName());
                    Glide.with(context).load(dataSet.get(listPosition).getImage()).into(imageView);
                    productRating.setRating(Float.parseFloat(String.valueOf(dataSet.get(listPosition).getRating())));
                    productCost.setText("RM " + dataSet.get(listPosition).getPrice());
                    productDiscount.setText(dataSet.get(listPosition).getDiscount());
                    if (dataSet.get(listPosition).getSpecial().trim().length() != 0) {
                        myViewHolder.special.setText("RM " + dataSet.get(listPosition).getSpecial());
                        strikeThroughText(productCost);
                    }
                    break;

                case LOADING:
                    LoadingVH loadingVH = (LoadingVH) holder;
                    if (retryPageLoad) {
                        loadingVH.mErrorLayout.setVisibility(View.VISIBLE);
                        loadingVH.mProgressBar.setVisibility(View.GONE);
                        loadingVH.mErrorTxt.setText(
                                errorMsg != null ?
                                        errorMsg :
                                        context.getString(R.string.error_msg_unknown));

                    } else {
                        loadingVH.mErrorLayout.setVisibility(View.GONE);
                        loadingVH.mProgressBar.setVisibility(View.VISIBLE);
                    }
                    break;
            }

        }

        private void strikeThroughText(TextView price) {
            price.setPaintFlags(price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
        }


        @Override
        public int getItemCount() {
            return dataSet == null ? 0 : dataSet.size();
            //return dataSet.size();
        }

        @Override
        public int getItemViewType(int position) {
            return (position == dataSet.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
        }
        public com.example.it.camanagement.model.CategoryProduct getItem(int position) {
            return dataSet.get(position);
        }

        public static class MyViewHolder extends RecyclerView.ViewHolder {

            TextView productName, productColor, productCost, productDistCount, product_id, productModel, productQuantity, special;
            RatingBar productRasting;
            ImageView productImage;


            public MyViewHolder(View itemView) {
                super(itemView);
                this.productName = (TextView) itemView.findViewById(R.id.product_name);
                this.productColor = (TextView) itemView.findViewById(R.id.product_color);
                this.productCost = (TextView) itemView.findViewById(R.id.cost);
                this.productDistCount = (TextView) itemView.findViewById(R.id.discount);
                this.productRasting = (RatingBar) itemView.findViewById(R.id.product_rating);
                this.product_id = (TextView) itemView.findViewById(R.id.product_iid);
                this.productQuantity = (TextView) itemView.findViewById(R.id.quantity);
                this.productModel = (TextView) itemView.findViewById(R.id.modelProduct);
                //this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
                this.productImage = (ImageView) itemView.findViewById(R.id.product_image);
                this.special = (TextView) itemView.findViewById(R.id.special);

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Context context = v.getContext();
                        Intent i = new Intent(context, ProductDescription.class);
                        i.putExtra("productName", ((TextView) v.findViewById(R.id.product_name)).getText().toString());
                        i.putExtra("product_id", ((TextView) v.findViewById(R.id.product_iid)).getText().toString());
                        context.startActivity(i);
                        if (getPosition() == 0) {

                            // Toast.makeText(v.getContext(), " On CLick one", Toast.LENGTH_SHORT).show();

                        }
                        if (getPosition() == 1) {
                            //Toast.makeText(v.getContext(), " On CLick Two", Toast.LENGTH_SHORT).show();

                        }
                        if (getPosition() == 2) {
                            // Toast.makeText(v.getContext(), " On CLick Three", Toast.LENGTH_SHORT).show();

                        }
                        if (getPosition() == 3) {//
                            // Toast.makeText(v.getContext(), " On CLick Fore", Toast.LENGTH_SHORT).show();

                        }

                    }
                });
            }
        }

        protected class LoadingVH extends RecyclerView.ViewHolder {
            private ProgressBar mProgressBar;
            private ImageButton mRetryBtn;
            private TextView mErrorTxt;
            private LinearLayout mErrorLayout;

            public LoadingVH(View itemView) {
                super(itemView);
                mProgressBar = (ProgressBar) itemView.findViewById(R.id.loadmore_progress);
                mRetryBtn = (ImageButton) itemView.findViewById(R.id.loadmore_retry);
                mErrorTxt = (TextView) itemView.findViewById(R.id.loadmore_errortxt);
                mErrorLayout = (LinearLayout) itemView.findViewById(R.id.loadmore_errorlayout);
            }


        }

    }









//Recycler View



     categoryProduct = (RecyclerView) findViewById(R.id.categoryProductList);
 categoryProductAdapter = new CategoryProduct(categoryProduct,categoryProductList, context);
                categoryProduct.setAdapter(categoryProductAdapter);
                categoryProduct.setNestedScrollingEnabled(false);
                categoryProduct.setHasFixedSize(false);
                girdLayoutManager = new GridLayoutManager(CategoryDetails.this, 2);
        categoryProduct.setLayoutManager(girdLayoutManager);

//scroll Listener 



 scrollListener = new EndlessRecyclerViewScrollListener(girdLayoutManager) {
        @Override
        public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
            // Triggered only when new data needs to be appended to the list
            // Add whatever code is needed to append new items to the bottom of the list
            Log.d("pageCount", "" + page);
           Log.d("FirstVisibleITEM", "" + girdLayoutManager.findFirstVisibleItemPosition());
           Log.d("LastVisibleITEM", "" + girdLayoutManager.findLastVisibleItemPosition());
}
    };
    categoryProduct.addOnScrollListener(scrollListener);

1 个答案:

答案 0 :(得分:0)

最后解决了它,问题是:我正在创建布局管理器的对象两次。方法中的一个(接收到API响应并通知适配器后)和OnCreate()活动方法中的另一个。从方法中删除一个对象(收到API响应并通知适配器后),修复了问题。