从RecyclerView获取可见和不可见的项目 [英] Getting visible and Non-visible items from RecyclerView

查看:1975
本文介绍了从RecyclerView获取可见和不可见的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的简单代码仅获取所有可见项目,但我需要获取所有项目(可见和不可见).

This simple code below ONLY gets all visible items, but I need to get all items (both Visible and non-visible).

是否有可能完全获得所有物品以及如何获得?

Is this possible to get completely all Items and how?

// This gets only visible items
final RecyclerView.ViewHolder holder = recyclerView.findViewHolderForAdapterPosition(index);

// Same as this
final View child = recyclerView.getChildAt(index);
final RecyclerView.ViewHolder holder = recyclerView.getChildViewHolder(child);

我也对与此相关的任何工作感兴趣.如果可能的话.

I am also interested in any work around this. If possible.

推荐答案

我相信这个问题是在 3年前首先提出的.

I believe this question was first asked 3 years ago.

在第一个视图上,正如 Pawel 所指出的那样,您似乎要求的是不可能,因为除非感兴趣的视图实际可见,否则相应的ViewHolder可能会或可能不存在-而且显然没有任何本地方法可以强制其创建.

On first view, as Pawel points out, it seems that you are asking for the impossible, because unless the View of interest is actually visible then the corresponding ViewHolder may or may not exist - and there is apparently no native method to force it's creation.

我的要求是要远程确定

实现此目标的策略是通过滚动到所需项来强制创建 ViewHolder ,然后通过回调返回新创建的ViewHolder.

Strategy for achieving this was to force ViewHolder creation by scrolling to the desired item then returning the newly-created ViewHolder via callback.

该解决方案并非易事,但我相信代码已被很好地记录下来.我建议您将静态方法和接口复制到实用程序类中,然后根据虚拟 exampleOfUse()方法进行部署.如果您不能按原样使用它们 ,请告诉我.

The solution is non-trivial but I trust the code is well documented. I suggest you copy the static methods and interface into a utility class and deploy them as per the dummy exampleOfUse() method. If you cannot use them as is, please let me know.

我仅包括2种与滚动相关的方法,以确保完整性.忽略我的记录器: lg()

I have included the 2 scroll-related methods for completeness only. Ignore my logger: lg()

请记住,预滚动到所需项目是您获得ViewHolder的价格-因此可以发出 notifyItemChanged(). [适合我,但可能不是所有人. ]

Bear in mind that pre-scrolling to the desired item is the price you pay for getting to the ViewHolder - and therefore the ability to issue notifyItemChanged(). [ Suited me, but maybe not everyone. ]

// ---------------------------------------------------------------------------------------------
//  These 3 static methods provide:
//      (A) Smooth or direct scrolling for any RecyclerView. [ ScrollTo() ]
//      (B) A technique for obtaining the ViewHolder of any item (visible or otherwise).
//          [ Achieved via callback when scroll to desired position has completed. ]
//          [ Why: (e.g.) To highlight an externally selected (or any) RecyclerView item ]
// ---------------------------------------------------------------------------------------------

/** Sample method of use */
public void dummyExampleOfUse(RecyclerView rv, int pos) {
    getAnyViewHolder(rv, pos, true, new GetAnyViewHolder() {
        @Override
        public void scrollForViewHolder(RecyclerView.ViewHolder vh, int pos) {
            if (vh==null) lg("Failed!!!");      // <-- Your logger
            //else ((YourViewHolder)vh).yourViewHolderMethod(pos);
            // yourViewHolderMethod would typically issue notifyItemChanged(pos);
        }
    });
}

/** Interface to receive requested ViewHolder */
public interface GetAnyViewHolder {
    void scrollForViewHolder(RecyclerView.ViewHolder vh, int pos);
}

/** RecyclerView scroll with callback returning desired ViewHolder */
public static boolean getAnyViewHolder(RecyclerView rv, int pos, boolean smooth, GetAnyViewHolder cb) {
    if (rv==null) return false;
    if (rv.getAdapter() == null) return false;
    if (rv.getAdapter().getItemCount() < 1) return false;
    if (pos <0 || pos > rv.getAdapter().getItemCount()-1) return false;
    rv.addOnScrollListener(new MPA_SL(rv, cb, pos));
    scrollTo(rv, pos, smooth, null);       // Note user-specified scroll action!
    return true;
}

/** Custom Scroll listener needed for 'getAnyViewHolder()' */
private static class MPA_SL extends RecyclerView.OnScrollListener {
    RecyclerView rv; GetAnyViewHolder gavh; int pos;
    MPA_SL( RecyclerView rv,GetAnyViewHolder gavh, int pos ) {  // Constructor
        this.rv = rv; this.gavh = gavh; this.pos = pos;}
    @Override public void onScrollStateChanged(@NonNull RecyclerView rv, int newState) {
        super.onScrollStateChanged(rv, newState);
        lg(format("Scroll state: %d", newState));
        if(newState == RecyclerView.SCROLL_STATE_IDLE) {
            RecyclerView.ViewHolder vh = rv.findViewHolderForAdapterPosition(pos);
            gavh.scrollForViewHolder(vh, pos);      // Notify user
            rv.removeOnScrollListener(this);        // Self-destruct
        }
    }
}

/** Scroll according to speed */
public static void scrollTo(RecyclerView rv, int os, boolean smooth, TextView tv) {
    try {
        if (smooth) { smoothScroll(rv, os); }
        else { rv.scrollToPosition(os); }
    } catch ( IllegalArgumentException ile) {
        if (tv==null) {
            lg(format("Scroll error: %s", ile.getMessage()));
            return;
        }
        String msg = tv.getText().toString() + " ";
        msg += ile.getMessage();
        tv.setText(msg);
    }
}

/** Smoothly scroll to specified position at 1/4 speed */
private static void smoothScroll(RecyclerView rv, int position) throws IllegalArgumentException {
    RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(gc()) {
        @Override protected int getVerticalSnapPreference() {
            return LinearSmoothScroller.SNAP_TO_START;
        }
        @Override protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
            float millesecondsPerPixel = super.calculateSpeedPerPixel(displayMetrics);
            return millesecondsPerPixel * 4;
        }
    };
    smoothScroller.setTargetPosition(position);
    rv.getLayoutManager().startSmoothScroll(smoothScroller);
}

祝你好运!

这篇关于从RecyclerView获取可见和不可见的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆