如何在回收站适配器外部的回收站视图中获取当前商品的位置

时间:2019-08-15 05:24:56

标签: android android-recyclerview

我正在整个屏幕上显示一个回收站视图,该回收站视图只有一个图像视图,我想知道我如何才能在回收站适配器之外获取屏幕上显示的imageview的位置。

我尝试实现一个接口,但结果不准确。我想立即保存当前位置。

我的回收站适配器:

    public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHOlder> {
    private List<ImageList> mlist;
    private showPageNumber page;
    public RecyclerAdapter(List<ImageList> dataList, showPageNumber page) {
        mlist = dataList;
        this.page = page;
    }

    @NonNull
    @Override
    public MyViewHOlder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item,parent,false);
        return new MyViewHOlder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHOlder holder,int position) {
        Picasso.get().load(mlist.get(position).getUrl()).into(holder.photoView);
        page.showPage(position);
        holder.pageNumber.setText(position+1+"");
    }

    @Override
    public int getItemCount() {
        return mlist.size();
    }

    class MyViewHOlder extends RecyclerView.ViewHolder{
        ImageView photoView;
        TextView pageNumber;

        public MyViewHOlder(@NonNull View itemView) {
            super(itemView);
            photoView = itemView.findViewById(R.id.pdfImage);
            pageNumber = itemView.findViewById(R.id.pageNumber);

        }
    }
    public interface showPageNumber{
        void showPage(int position);
    }
}

每当我在MainActivity上实现showPageNumber接口时,showPage方法在滚动回收器视图中的项目时都不会给出准确的结果。

1 个答案:

答案 0 :(得分:0)

我不确定您要完成什么,但是如果您想找出当前显示的项目,则可以尝试以下操作:

假设您在RecyclerView上使用LinearLayoutManager,则可以收听Scroll事件,评估滚动后ReclycerView稳定后显示哪个页面

RecyclerView recyclerView = findViewById(R.id.rcv);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        // if you just want to know if the new "page" is completely visible
        if(newState == RecyclerView.SCROLL_STATE_SETTLING){
            int pagePosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();

            // if you just want to know if the new "page" comes in view
            int pagePosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
        }
    }
});