item不可见 recycleview_从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.

解决方案

I believe this question was first asked 3 years ago.

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.

My requirement was for the visibility and highlighting of any item in the dataset to be determined remotely!

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

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.

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

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!!!"); //

//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);

}

Good luck!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值