layoutmanager.FindFirstCompletelyVisibleItemPosition always returns -1 - android

I have a recyclerview in my android project which displays media contents within each view. What I'm trying to achieve is that I'm able to play/pause media as I scroll up and down. I need to get the adapter position of the completely visible view. I'm doing something like this.
In my activity fragment I have this:
layoutmanager = new LinearLayoutManager(Activity);
adapter = new FeedAdapter(vid, userName, this.Context);
feeditem.SetLayoutManager(layoutmanager);
feeditem.SetAdapter(adapter);
var onScrollListener = new XamarinRecyclerViewOnScrollListener(Activity, layoutmanager, adapter);
The scroll listener event looks like this:
public override void OnScrollStateChanged(RecyclerView recyclerView, int newState)
{
base.OnScrollStateChanged(recyclerView, newState);
if (newState == (int)ScrollState.Idle)
{
layoutmanager = (LinearLayoutManager)recyclerView.GetLayoutManager();
int firstVisiblePosition = layoutmanager.FindFirstCompletelyVisibleItemPosition();
int visible = layoutmanager.FindFirstVisibleItemPosition();
int last = layoutmanager.FindLastVisibleItemPosition();
if (firstVisiblePosition >= 0)
{
if (oldFocusedLayout != null)
{
Toast.MakeText(ctx, "Stop Video", ToastLength.Long).Show();
}
}
currentFocusedLayout = layoutmanager.FindViewByPosition(firstVisiblePosition);
Toast.MakeText(ctx, "Play video", ToastLength.Long).Show();
oldFocusedLayout = currentFocusedLayout;
}
}
feeditem.AddOnScrollListener(onScrollListener);
The issue is that the linearlayout manager method FindFirstCompletelyVisibleItemPosition always returns -1 even when the view is completely visible. Other methods like FindFirstVisibleItemPosition and FindLastVisibleItemPosition gives the correct position of the view.
Any idea what might be the issue here?

layoutManager.findFirstCompletelyVisibleItemPosition()
FROM DOCUMENT
Returns the adapter position of the FIRST FULLY VISIBLE view. This position does not include adapter changes that were dispatched after the last layout pass.
It mean that, at least one listitem view should be fully visible otherwise, it give -1 (NO_POSITION)
FROM TESTING
This will work and give correct position...
This won't work and give -1 (NO_POSITION), because two ListItem view is not fully visible.

Related

Check if child view of RecyclerView item is visible on screen

I have a scenario in which I need to know if a child view of a RecyclerView item is visible on screen.
In this case, each RecyclerView item has a TextView and I need to know if that TextView is fully visible on screen. I've already figured this part out, but now my question is this:
How can I make a call to the adapter from my fragment to let it know that the view is visible on screen? What best practice should I follow for this?
Here is my fragment class method where I get the visible child view:
private void getFirstVisibleChildView() {
int findFirstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
int findLastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
int [] positions = { findFirstVisibleItemPosition, findLastVisibleItemPosition };
PostAdapter.PostViewHolder viewHolder;
Rect scrollBounds = new Rect();
recyclerView.getDrawingRect(scrollBounds);
int[] location = new int[2];
for (int position : positions) {
RecyclerView.ViewHolder item = recyclerView.findViewHolderForAdapterPosition(position);
if (item instanceof PostAdapter.PostViewHolder) {
viewHolder = (PostAdapter.PostViewHolder) item;
viewHolder.getChildView().getLocationInWindow(location);
if (location[1] < 0 || location[1] > scrollBounds.bottom) {
// Not visible
} else {
// Visible
// How to call the RecyclerView adapter here and be able to manipulate it?
// Custom listener, direct call to ViewHolder, or some other method?
}
}
}
}
Thanks!
You can set addOnScrollListener on the RecyclerView, so it checkes if your specific view is fully shown whenever it's scrolled
And normally create a custom method in your adapter that you want to call within this listener when the above condition is met.
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (mRecyclerViewTafsir.getLayoutManager() == null) return;
// Here you can check if the particular textView is fully
// appeared on the screen >> You already did this part
mAdapter.callBack(); // call a method in the adapter when the condition is met
}
});

How to tell RecyclerView to start at specific item position

I want my RecyclerView with LinearLayoutManager to show up with scroll position at specific item after adapter got updated. (not first/last position)
Means the at first (re-)layout, this given position should be in visible area.
It should not layout with position 0 on top and scroll afterwards to target position.
My Adapter starts with itemCount=0, loads its data in thread and notifies its real count later. But the start position must be set already while count is still 0!
As of now I used some kind of post Runnable containingscrollToPosition but this has side effects (starts at first pos and jumps immediately to target position (0 -> target) and seems not to work well with DiffUtil (0 -> target -> 0))
Edit: To clearify: I need alternative to layoutManager.setStackFromEnd(true);, something like setStackFrom(position). ScrollToPosition does not work, if I call it when itemCount is still 0, so it gets ignored. If I call it when I notify that itemCount is now >0, it will layout from 0 and jumps short after to target position. And it fails completely if I use DiffUtil.DiffResult.dispatchUpdatesTo(adapter)`. (shows from 0, then scrolls to target position and then again back to position 0)
I found a solution myself:
I extended the LayoutManager:
class MyLayoutManager extends LinearLayoutManager {
private int mPendingTargetPos = -1;
private int mPendingPosOffset = -1;
#Override
public void onLayoutChildren(Recycler recycler, State state) {
if (mPendingTargetPos != -1 && state.getItemCount() > 0) {
/*
Data is present now, we can set the real scroll position
*/
scrollToPositionWithOffset(mPendingTargetPos, mPendingPosOffset);
mPendingTargetPos = -1;
mPendingPosOffset = -1;
}
super.onLayoutChildren(recycler, state);
}
#Override
public void onRestoreInstanceState(Parcelable state) {
/*
May be needed depending on your implementation.
Ignore target start position if InstanceState is available (page existed before already, keep position that user scrolled to)
*/
mPendingTargetPos = -1;
mPendingPosOffset = -1;
super.onRestoreInstanceState(state);
}
/**
* Sets a start position that will be used <b>as soon as data is available</b>.
* May be used if your Adapter starts with itemCount=0 (async data loading) but you need to
* set the start position already at this time. As soon as itemCount > 0,
* it will set the scrollPosition, so that given itemPosition is visible.
* #param position
* #param offset
*/
public void setTargetStartPos(int position, int offset) {
mPendingTargetPos = position;
mPendingPosOffset = offset;
}
}
It stores my target position. If onLayoutChildren is called by RecyclerView, it checks if adapters itemCount is already > 0. If true, it calls scrollToPositionWithOffset().
So I can tell immediately what position should be visible, but it will not be told to LayoutManager before position exists in Adapter.
You can try this, it will scroll to a position you want:
rv.getLayoutManager().scrollToPosition(positionInTheAdapter).
If you want to scroll to a specific position and that position is the adapter's position, then you can use StaggeredGridLayoutManager scrollToPosition
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
staggeredGridLayoutManager.scrollToPosition(10);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
If I understand the question, you want to scroll to a specific position but that position is the adapter's position and not the RecyclerView's item position.
You can only achieve this through the LayoutManager.
rv.getLayoutManager().scrollToPosition(youPositionInTheAdapter);
None of the methods above worked for me. I did the following using ViewTreeObserver that is triggered once its children have been added/changed visibility.
recyclerView.apply {
adapter = ...
layoutManager = ...
val itemCount = adapter?.itemCount ?: 0
if(itemCount > 1) {
viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
viewTreeObserver.removeOnGlobalLayoutListener(this)
(layoutManager as? LinearLayoutManager)?.scrollToPosition(#PositionToStartAt)
}
}
}
Go ahead and set #PositionToStartAt to a specific value. You can also ensure that the RecyclerView initial position setting gets triggered once a specific number of children have been laid out to ensure it is set correctly.
if(recyclerView.childCount() > #PositionCheck) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
(layoutManager as? LinearLayoutManager)?.scrollToPosition(#PositionToStartAt)
}
If your only motive is to start the recyclerView from a specific position without any scroll-like animation I'll suggest using StaggeredGridLayoutManager
val staggeredGridLayoutManager = StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL)//or VERTICAL
staggeredGridLayoutManager.scrollToPosition(specificPosition)
recyclerView.apply{
layoutManager = staggeredGridLayoutManager
}
Another contribution to a long running question...
As mentioned, layoutManager.scrollToPosition/WithOffset() does work to get the RecyclerView positioned, but timing this can be tricky. For example with variable length item views the RecyclerView has to work hard to get all the prior item views measured.
The approach below simply delays telling the RecyclerView about the prior items, then calls notifyItemRangeInserted(0, offset). This enabled the view to appear in the right place, with no visible scrolling at the start, and ready to scroll back.
private List<Bitmap> bitmaps = new ArrayList<>();
...
private class ViewAdapter extends RecyclerView.Adapter<ViewHolder> {
private volatile int offset;
private boolean offsetCancelled;
ViewAdapter(int initialOffset) {
this.offset = initialOffset;
this.offsetCancelled = initialOffset > 0;
}
#Override
public int getItemCount() {
return bitmaps.size() - offset;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
ImageView imageView = new ImageView(MyActivity.this); // Or getContext() from a Fragment
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(lp);
return new ViewHolder(imageView);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.imageView.setImageBitmap(bitmaps.get(position + offset));
if (!offsetCancelled) {
offsetCancelled = true;
recyclerView.post(() -> {
int previousOffset = offset;
offset = 0;
notifyItemRangeInserted(0, previousOffset);
Log.i(TAG, "notifyItemRangeInserted(0, " + previousOffset + ")");
});
}
}
}
private class ViewHolder extends RecyclerView.ViewHolder {
private final ImageView imageView;
ViewHolder(#NonNull ImageView itemView) {
super(itemView);
this.imageView = itemView;
}
}
For context, this is a full example, based around ImageView's and Bitmap's. The key bit is the use of the offset in getItemCount() and onBindViewHolder().

How to determine the most visible view position after the RecyclerView adapter data change?

I want to determine the most visible item in my RecyclerView and so I use the following method:
public int getMostVisibleIndex() {
// try to figure which child is the most visible on screen
LinearLayoutManager layoutManager = ((LinearLayoutManager) getLayoutManager());
mFirstVisibleIndex = layoutManager.findFirstVisibleItemPosition();
mLastVisibleIndex = layoutManager.findLastVisibleItemPosition();
// How do I use convertPreLayoutPositionToPostLayout() ?
VisibleIndex mostVisible = null;
if (mFirstVisibleIndex != -1|| mLastVisibleIndex != -1) {
// if it's not the same
if (mFirstVisibleIndex != mLastVisibleIndex) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) this.getLayoutManager();
// get the visible rect of the first item
Rect firstPercentageRect = new Rect();
linearLayoutManager.findViewByPosition(mFirstVisibleIndex).getGlobalVisibleRect(firstPercentageRect);
// get the visible rect of the last item
Rect lastPercentageRect = new Rect();
linearLayoutManager.findViewByPosition(mLastVisibleIndex).getGlobalVisibleRect(lastPercentageRect);
// since we're on a horizontal list
if (firstPercentageRect.width() > lastPercentageRect.width()) {
return mFirstVisibleIndex;
} else {
return mLastVisibleIndex;
}
} else {
return mFirstVisibleIndex;
}
}
return -1;
}
It works great, but after I change the data set, and call any notify*Changed methods in my adapter, if I try to use the above function, the item positions that findFirstVisibleItemPosition and findLastVisibleItemPosition return are wrong.
I noticed that they both use getlayoutposition behind the scenes, and I also noticed that on the documentation it says:
If LayoutManager needs to call an external method that requires the adapter position of the item, it can use getAdapterPosition() or convertPreLayoutPositionToPostLayout(int).
It sounds as if convertPreLayoutPositionToPostLayout is EXACTLY what I'm looking for, but I have no idea how to access it from within a RecyclerView.
Any ideas?
Thank you.
In my case I can only have maximum 2 visible views at a time in recyclerview and
I am using this method in onScrolled for always having the mostVisibleItemPosition
for playing video content when user scrolls.
So getTop() returns top position of this view relative to its parent and when user starts scrolling firstView is getting out of the screen and the firstView.getTop() will return minus value while secondView.getTop() is positive and when secondView top reaches nearly the center of the screen getting absolute value of firstView.getTop() we will determine how many pixels firstView top is above from parent view top and getting secondView.getTop() we will determine how many pixels secondView top is above parent bottom and this is where mostVisibleItemPosition will changed.
private void detectMostVisibleItem() {
int firstItemPosition = layoutManager.findFirstVisibleItemPosition();
int secondItemPosition = layoutManager.findLastVisibleItemPosition();
if (firstItemPosition == secondItemPosition) {
mostVisibleItemPosition = firstItemPosition;
} else {
View firstView = layoutManager.findViewByPosition(firstItemPosition);
View secondView = layoutManager.findViewByPosition(secondItemPosition);
if (Math.abs(firstView.getTop()) <= Math.abs(secondView.getTop())) {
if (mostVisibleItemPosition != firstItemPosition) {
mostVisibleItemPosition = firstItemPosition;
...
}
} else {
if (mostVisibleItemPosition != secondItemPosition) {
mostVisibleItemPosition = secondItemPosition;
...
}
}
}
}

scrollBy doesn't work properly in nested recyclerview

I have a vertically scrolling RecyclerView with horizontally scrolling inner RecyclerViews just like this.
With this implementation, users can scroll each horizontal recyclerview synchronously. However, when a user scroll vertically to the parent recyclerView, a new horizontal recyclerview which has just attached on window doesn't display on same scroll x position. This is normal. Because it has just created.
So, I had tried to scroll to the scrolled position before it was displayed. Just like this:
Note: this is in adapter of the parent recyclerview whose orientation is vertical.
#Override
public void onViewAttachedToWindow(RecyclerView.ViewHolder holder) {
super.onViewAttachedToWindow(holder);
CellColumnViewHolder viewHolder = (CellColumnViewHolder) holder;
if (m_nXPosition != 0) {
// this doesn't work properly
viewHolder.m_jRecyclerView.scrollBy(m_nXPosition, 0);
}
}
As you can see, scrollBy doesn't effect for row 10, row 11, row 12 and row 13 After that, I debugged the code to be able find out find out what's happening. When I set scroll position using scrollBy, childCount() return zero for row 10, row 11, row 12 and row 13 So they don't scroll. But why ? and Why others work ?
How can I fix this ?
Is onViewAttachedToWindow right place to scroll new attached recyclervViews ?
Note: I have also test scrollToPosition(), it doesn't get any problem like this. But I can't use it at my case. Because users can scroll to the any x position which may not the exact position. So I need to set scroll position using x value instead of the position.
Edit: You can check The source code
I found a solution that is use scrollToPositionWithOffset method instead using scrollBy. Even if both of two scroll another position, they have really different work process in back side.
For example: if you try to use scrollBy to scroll any pixel position and your recyclerView had not been set any adapter which means there is no any data to display and so it has no any items yet, then scrollBy doesn't work. RecyclerView uses its layoutManager's scrollBy method. So in my case, I am using LinearLayoutManager to the horizontal recyclerViews.
Lets see what it's doing :
int scrollBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
if (getChildCount() == 0 || dy == 0) {
return 0;
}
mLayoutState.mRecycle = true;
ensureLayoutState();
final int layoutDirection = dy > 0 ? LayoutState.LAYOUT_END : LayoutState.LAYOUT_START;
final int absDy = Math.abs(dy);
updateLayoutState(layoutDirection, absDy, true, state);
final int consumed = mLayoutState.mScrollingOffset
+ fill(recycler, mLayoutState, state, false);
if (consumed < 0) {
if (DEBUG) {
Log.d(TAG, "Don't have any more elements to scroll");
}
return 0;
}
final int scrolled = absDy > consumed ? layoutDirection * consumed : dy;
mOrientationHelper.offsetChildren(-scrolled);
if (DEBUG) {
Log.d(TAG, "scroll req: " + dy + " scrolled: " + scrolled);
}
mLayoutState.mLastScrollDelta = scrolled;
return scrolled;
}
As you can see scrollBy ignores the scroll intentions if there is no any child at that time.
if (getChildCount() == 0 || dy == 0) {
return 0;
}
On the other hand scrollToPosition can work perfectly even if there is no any set data yet.
According to the Pro RecyclerView slide, the below sample works perfectly. However you can not do that with scrollBy.
void onCreate(SavedInstanceState state) {
....
mRecyclerView.scrollToPosition(selectedPosition);
mRecyclerView.setAdapter(myAdapter);
}
As a result, I have changed little thing to use scrollToPositionWithOffset().
Before this implementation I was calculating the exact scroll x position as a pixel.
After that, when the scroll came idle state, calculating the first complete visible position to the first parameter of the scrollToPositionWithOffset().
For second parameter which is the offset, I am getting the value using view.getLeft() function which helps to get left position of this view relative to its parent.
And it works perfectly!!

RecyclerView scrolls to end after smoothScrollToPosition(0)

I have RecyclerView with LinearLayoutManager (Vertical, not inverted). When I insert or move item to 0 position, such method is invoked:
private void scrollToStart() {
int firstVisiblePosition = ((LinearLayoutManager) recentList.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
boolean notScrolling = recentList.getScrollState() == RecyclerView.SCROLL_STATE_IDLE;
if (firstVisiblePosition < 2 && notScrolling) {
recentList.scrollToPosition(0);
}
}
But sometimes it smooth scrolls to the end of list.
(I've seen such behaviour in some apps like Instagram. It looks like list scrolls to top and then starts to move in the opposite direction.)
If I replace smoothScrollToPosition with simple scrollToPosition, it behaves as it should.
How to prevent this scroll?
In my case the fact items are recyclable was the cause to it. Try to place this.setIsRecyclable(false); inside of your ViewHolder

Categories

Resources