I have a recycler view that looks like this:
At the start, these circle icons are empty. I need to update every icon of my recycler to be from empty to full within an interval of 5 seconds (see the image above).
I actually can update these icons, but my problem is:
If I have 20 items, I'll need to scroll the recycler in order to see every item. Whenever I scroll the recycler, the last 4-5 items don't get updated from empty to full.
I just need to update the UI, I don't need to remove or add anything to the recyclerview. I've already tried to use notifyDataSetChanged(), notifyItemChanged(), but nothing worked so far.
What's your suggestion? Thank you in advance
Here's one strategy. Have one function in your adapter to start/reset the animation. You can call it when you set the data list. In onBindViewHolder you calculate when relative to now the icon should change to filled (could be in the past). The ViewHolder class either immediately shows the filled icon if the time is negative, or else it posts a delayed runnable to change it in the future. You'll need to cancel any previous delayed runnable so when views get recycled, they always get updated to the correct state.
//Inside your ViewHolder class:
private val setIconRunnable = Runnable { setFilledIcon() }
fun fillIconAt(timeFromNowMillis: Long) {
itemView.removeCallbacks(setIconRunnable)
if (timeFromNowMillis <= 0L) {
setFilledIcon()
} else {
setEmptyIcon()
itemView.postDelayed(setIconRunnable, timeFromNowMillis)
}
}
// In your adapter class:
companion object {
private const val ANIMATION_DURATION = 5000L
}
private var animationStartTime = 0L
fun initiateIconAnimation() {
animationStartTime = System.currentTimeMillis()
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: YourViewHolderType, position: Int) {
//...
val iconChangeTime = (
ANIMATION_DURATION * (position + 1).toFloat() / yourDataList.size
).roundToLong() + animationStartTime
holder.fillIconAt(iconChangeTime - System.currentTimeMillis())
}
I have a recyclerview with gridlayoutmanager.
If I run the code
recycler.smoothScrollTo(adapter.getItemCount())
the recycler scrolls really fast to the last element. I tried some solutions on Stackoverflow to make the scrolling slower, but all apply to Linearlayoutmanager not Gridlayoutmanager.
Any help?
I cannot say for sure what your problem is. But I am lucky enough to have a very simple GridLayoutManager recyclerview demo out there, very small sample project. I created a so branch and added a button that does the same you do.
Look it up: https://github.com/Gryzor/GridToShowAds/compare/so?expand=1
.setOnClickListener { mainRecyclerView.smoothScrollToPosition(data.size) }
And that alone just works.
Check the source code, it's a very simple sample for something unrelated, but happens to have a RV with a Grid Layout :)
UPDATE
What you actual want is to control the Speed at which the recyclerView scrolls. Ok.
It's not the RecyclerView that drives the scroll, it's actually the LayoutManager that does. How so?
If you look at RV's source code...
public void smoothScrollToPosition(int position) {
...
mLayout.smoothScrollToPosition(this, mState, position);
}
So it ends up calling mLayout. What is this?
#VisibleForTesting LayoutManager mLayout;
So, your LayoutManager#smoothScroll... method is used.
Decompiling now GridLayoutManager for science:
#Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
int position) {
LinearSmoothScroller linearSmoothScroller =
new LinearSmoothScroller(recyclerView.getContext());
linearSmoothScroller.setTargetPosition(position);
startSmoothScroll(linearSmoothScroller);
}
note: this method is actually in LinearLayoutManager because GridLayoutManager is a subclass and it doesn't override the method
A LinearSmoothScroller!; no parameter to specify the speed though...
Look at it:
public class LinearSmoothScroller extends RecyclerView.SmoothScroller {
private static final boolean DEBUG = false;
private static final float MILLISECONDS_PER_INCH = 25f;
private static final int TARGET_SEEK_SCROLL_DISTANCE_PX = 10000;
...
}
This class has a start() method described as:
* Starts a smooth scroll for the given target position.
So who calls this?
The mLayout.smoothScrollToPosition method does at the end in the startSmoothScroll(...) call.
public void startSmoothScroll(SmoothScroller smoothScroller) {
Starts a smooth scroll using the provided {#link SmoothScroller}.
mSmoothScroller.start(mRecyclerView, this);
So... in lieu of all this, the answer to your question is:
You need to create your extension of GridLayoutManager by subclassing it, and in it, override the smoothScrollToPosition method, to provide your own Scroller logic.
Thread carefully though, LayoutManagers are not the "simplest" classes of all time and they can be quite complicated to master.
Good luck! :)
My simple working solution currently is still implementing a timer then working with it.
final CountDownTimer scrollUp_timer = new CountDownTimer(50000, 30) {
#Override
public void onTick(long millisUntilFinished) {
if (layoutManager != null && layoutManager.findFirstVisibleItemPosition() != 0) searchRecyclerView.smoothScrollToPosition(layoutManager.findFirstVisibleItemPosition()-1);
}
#Override
public void onFinish() {
try{
}catch(Exception e){
// log
}
}
};
scrollUp.setOnDragListener(new View.OnDragListener() {
#Override
public boolean onDrag(View view, DragEvent dragEvent) {
layoutManager = ((GridLayoutManager)searchRecyclerView.getLayoutManager());
int action = dragEvent.getAction();
if (action == DragEvent.ACTION_DRAG_ENTERED) {
scrollUp_timer.start();
} else if (action == DragEvent.ACTION_DRAG_EXITED) {
searchRecyclerView.scrollBy(0,0);
scrollUp_timer.cancel();
}
return true;
}
});
You can extend:
class CSCustomRecyclerSmoothScroller(context: Context, speed: Float = 0.2f)
: LinearSmoothScroller(context) {
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float = speed
}
And use it like:
val shortAnimationDuration =
view.resources.getInteger(android.R.integer.config_shortAnimTime)
val scroller = CSCustomRecyclerSmoothScroller(this, speed = 0.15)
scroller.targetPosition = position
view.postDelayed({
layoutManager.startSmoothScroll(scroller)
}, shortAnimationDuration.toLong())
postDelayed can be necessary in some cases but maybe not in all.
I use similar code with GridLayoutManager I just tried to extract relevant parts from my way of writing things.
I have implemented a horizontal scrollable RecyclerView. My RecyclerView uses a LinearLayoutManager, and the problem I am facing is that when I try to use scrollToPosition(position) or smoothScrollToPosition(position) or from LinearLayoutManager's scrollToPositionWithOffset(position). Neither works for me. Either a scroll call doesn't scroll to the desired location or it doesn't invoke the OnScrollListener.
So far I have tried so many different combinations of code that I cannot post them all here. Following is the one that works for me (But only partially):
public void smoothUserScrollTo(final int position) {
if (position < 0 || position > getAdapter().getItemCount()) {
Log.e(TAG, "An attempt to scroll out of adapter size has been stopped.");
return;
}
if (getLayoutManager() == null) {
Log.e(TAG, "Cannot scroll to position a LayoutManager is not set. " +
"Call setLayoutManager with a non-null layout.");
return;
}
if (getChildAdapterPosition(getCenterView()) == position) {
return;
}
stopScroll();
scrollToPosition(position);
if (lastScrollPosition == position) {
addOnLayoutChangeListener(new OnLayoutChangeListener() {
#Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
if (left == oldLeft && right == oldRight && top == oldTop && bottom == oldBottom) {
removeOnLayoutChangeListener(this);
updateViews();
// removing the following line causes a position - 3 effect.
scrollToView(getChildAt(0));
}
}
});
}
lastScrollPosition = position;
}
#Override
public void scrollToPosition(int position) {
if (position < 0 || position > getAdapter().getItemCount()) {
Log.e(TAG, "An attempt to scroll out of adapter size has been stopped.");
return;
}
if (getLayoutManager() == null) {
Log.e(TAG, "Cannot scroll to position a LayoutManager is not set. " +
"Call setLayoutManager with a non-null layout.");
return;
}
// stopScroll();
((LinearLayoutManager) getLayoutManager()).scrollToPositionWithOffset(position, 0);
// getLayoutManager().scrollToPosition(position);
}
I opted for scrollToPositionWithOffset() because of this but the case perhaps is different as I use a LinearLayoutManager instead of GridLayoutManager. But the solution does work for me too, but as I said earlier only partially.
When the call to scroll is from 0th position to totalSize - 7 scroll works like a charm.
When scroll is from totalSize - 7 to totalSize - 3, First time I only scroll to 7th last item in the list. The second time however I can scroll fine
When scrolling from totalSize - 3 to totalSize, I start getting unexpected behavior.
If anyone has found a work around I'd Appreciate it. Here's the gist to my code of custom ReyclerView.
I had the same issue some weeks ago, and found only a really bad solution to solve it. Had to use a postDelayed with 200-300ms.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
yourList.scrollToPosition(position);
}
}, 200);
If you found a better solution, please let me know! Good luck!
Turns out I was having a similar issue until I utilized
myRecyclerview.scrollToPosition(objectlist.size()-1)
It would always stay at the top when only putting in the objectlist size. This was until i decided to set the size equal to a variable. Again, that didn't work. Then I assumed that perhaps it was handling an outofboundsexception without telling me. So I subtracted it by 1. Then it worked.
The accepted answer will work, but it may also break. The main reason for this issue is that the recycler view may not be ready by the time you ask it to scroll. The best solution for the same is to wait for the recycler view to be ready and then scroll. Luckily android has provided one such option. Below solution is for Kotlin, you can try the java alternative for the same, it will work.
newsRecyclerView.post {
layoutManager?.scrollToPosition(viewModel.selectedItemPosition)
}
The post runnable method is available for every View elements and will execute once the view is ready, hence ensuring the code is executed exactly when required.
You can use LinearSmoothScroller this worked every time in my case:
First create an instance of LinearSmoothScroller:
LinearSmoothScroller smoothScroller=new LinearSmoothScroller(activity){
#Override
protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
And then when you want to scroll recycler view to any position do this:
smoothScroller.setTargetPosition(pos); // pos on which item you want to scroll recycler view
recyclerView.getLayoutManager().startSmoothScroll(smoothScroller);
Done.
So the problem for me was that I had a RecyclerView in a NestedScrollView. Took me some time to figure out this was the problem. The solution for this is (Kotlin):
val childY = recycler_view.y + recycler_view.getChildAt(position).y
nested_scrollview.smoothScrollTo(0, childY.toInt())
Java (credits to Himagi https://stackoverflow.com/a/50367883/2917564)
float y = recyclerView.getY() + recyclerView.getChildAt(selectedPosition).getY();
scrollView.smoothScrollTo(0, (int) y);
The trick is to scroll the nested scrollview to the Y instead of the RecyclerView. This works decently at Android 5.0 Samsung J5 and Huawei P30 pro with Android 9.
I also faced a similar problem (having to scroll to the top when the list is getting updated), but none of the above options worked 100%
However I finally found a working solution at https://dev.to/aldok/how-to-scroll-recyclerview-to-a-certain-position-5ck4 archive link
Summary
scrollToPosition only seems to work when the underlying dataset is ready.
So therefore postDelay works (randomly) but it's depending on the speed of the device/app. If the timeout is too short it fails. smoothScrollToPosition also only works if the adapter is not too busy (see https://stackoverflow.com/a/61403576/11649486)
To observe when the dataset is ready, a AdapterDataObserver can be added and certain methods overridden.
The code that fixed my problem:
adapter.registerAdapterDataObserver( object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeInserted(
positionStart: Int,
itemCount: Int
) {
// This will scroll to the top when new data was inserted
recyclerView.scrollToPosition(0)
}
}
None of the methods seems to be working for me. Only the below single line of code worked
((LinearLayoutManager)mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(adapter.currentPosition(),200);
The second parameter refers to offset, which is actually the distance (in pixels) between the start edge of the item view and start edge of the RecyclerView. I have supplied it with a constant value to make the top items also visible.
Check for more reference over here
Using Kotlin Coroutines in Fragment or Activity, and also using the lifecycleScope since any coroutine launched in this scope is canceled when the Lifecycle is destroyed.
lifecycleScope.launch {
delay(100)
recyclerView.scrollToPosition(0)
This worked for me
Handler().postDelayed({
(recyclerView.getLayoutManager() as LinearLayoutManager).scrollToPositionWithOffset( 0, 0)
}, 100)
I had the same issue while creating a cyclic/circular adapter, where I could only scroll downward but not upward considering the position initialises to 0. I first considered using Robert's approach, but it was too unreliable as the Handler only fired once, and if I was unlucky the position wouldn't get initialised in some cases.
To resolve this, I create an interval Observable that checks every XXX amount of time to see whether the initialisation succeeded and afterward disposes of it. This approach worked very reliably for my use case.
private fun initialisePositionToAllowBidirectionalScrolling(layoutManager: LinearLayoutManager, realItemCount: Int) {
val compositeDisposable = CompositeDisposable() // Added here for clarity, make this into a private global variable and clear in onDetach()/onPause() in case auto-disposal wouldn't ever occur here
val initPosition = realItemCount * 1000
Observable.interval(INIT_DELAY_MS, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe ({
if (layoutManager.findFirstVisibleItemPosition() == 0) {
layoutManager.scrollToPositionWithOffset(initPosition, 0)
if (layoutManager.findFirstCompletelyVisibleItemPosition() == initPosition) {
Timber.d("Adapter initialised, setting position to $initPosition and disposing interval subscription!")
compositeDisposable.clear()
}
}
}, {
Timber.e("Failed to initialise position!\n$it")
compositeDisposable.clear()
}).let { compositeDisposable.add(it) }
}
This worked perfectly for when scrolling to last item in the recycler
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (((LinearLayoutManager) recyclerView.getLayoutManager())
.findLastVisibleItemPosition() != adapter.getItemCount() - 1) {
recyclerView.scrollToPosition(adapter.getItemCount() - 1);
handler.postDelayed(this, 200);
}
}
}, 200 /* change it if you want*/);
Pretty weird bug, anyway I managed to work around it without post or post delayed as follow:
list.scrollToPosition(position - 1)
list.smoothScrollBy(1, 0)
Hopefully, it helps someone too.
Had the same issue. My problem was, that I refilled the view with data in an async task, after I tried to scroll. From onPostExecute ofc fixed this problem. A Delay fixed this issue too, because when the scroll executed, the list had already been refilled.
I use below solution to make the selected item in recycler view visible after the recycler view is reloaded (orientation change, etc). It overrides LinearLayoutManager and uses onSaveInstanceState to save current recycler position. Then in onRestoreInstanceState the saved position is restored. Finaly, in onLayoutCompleted, scrollToPosition(mRecyclerPosition) is used to make the previously selected recycler position visible again, but as Robert Banyai stated, for it to work reliably a certain delay must be inserted. I guess it is needed to provide enough time for adapter to load the data before scrollToPosition is called.
private class MyLayoutManager extends LinearLayoutManager{
private boolean isRestored;
public MyLayoutManager(Context context) {
super(context);
}
public MyLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public MyLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
#Override
public void onLayoutCompleted(RecyclerView.State state) {
super.onLayoutCompleted(state);
if(isRestored && mRecyclerPosition >-1) {
Handler handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
MyLayoutManager.this.scrollToPosition(mRecyclerPosition);
}
},200);
}
isRestored=false;
}
#Override
public Parcelable onSaveInstanceState() {
Parcelable savedInstanceState = super.onSaveInstanceState();
Bundle bundle=new Bundle();
bundle.putParcelable("saved_state",savedInstanceState);
bundle.putInt("position", mRecyclerPosition);
return bundle;
}
#Override
public void onRestoreInstanceState(Parcelable state) {
Parcelable savedState = ((Bundle)state).getParcelable("saved_state");
mRecyclerPosition = ((Bundle)state).getInt("position",-1);
isRestored=true;
super.onRestoreInstanceState(savedState);
}
}
If you use recyclerview in nestedScrollView you must scroll nestScrollview
nestedScrollview.smoothScrollTo(0,0)
Maybe It's not so elegant way to do it, But this always works for me. Add a new method to the RecyclerView and use it insted of scrollToPosition:
public void myScrollTo(int pos){
stopScroll();
((LinearLayoutManager)getLayoutManager()).scrollToPositionWithOffset(pos,0);
}
The answer is to use the Post Method, it will guarantee correct execution for any action
This is the ultimate solution using kotlin in this date ... if you navigate to another fragment and go back and your recyclerview resets to the first position just add this line in onCreateView or wherever you need can call the adapter...
pagingAdapter.stateRestorationPolicy=RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
BTW pagingAdapter is my adapter with diffUtil.
I had a similar issue, (but not the same), I try to explain it, maybe be could help someone else:
By the time I call to 'scrollToPosition' dataset is already set but some content like images loaded async (using Glide library) and probably when RecyclerView tries to compute the height amount to scroll down, image should return 0 as no loaded yet. So that gives an inaccurate scroll down I could solve it that way:
fun LinearLayoutManager.accurateScrollToPosition(position: Int) {
this.scrollToPosition(position)
this.postOnAnimation {
val realPosition = this.findFirstVisibleItemPosition()
if (position != realPosition) {
this.accurateScrollToPosition(position)
} else {
this.scrollToPosition(position) // this looks redunadant or inecessary but must be call to ensure accurate scroll
}
}
}
PD: In my case was not possible to know the size of the image to be loaded, if you know or you can resize the image you can add a placeholder on glide with de image size or override de size so recyclerView can compute the size correctly and don't need the above walkaraound.
I'm having an unusual error. I have this inside a custom viewgroup. The method receives a view and add it to the layout but i keep getting the same error:
if((ViewGroup)view.getParent() != null){
((ViewGroup)view.getParent()).removeView(view);
}
addView(view); <--- Breakpoints puts the error on this line
The error is:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Using breakpoints around this shows that "view" even after calling removeView onthe parent keep a reference to its parent..
Some people proposed using a runnable to wait a few seconds before adding it to the view. I havent tried this because it seems more a hack than a solution.. Either way i hope someone may be able to help
Thanks!
PS: Not that it should matter but the parent of this view i'm adding is a custom grid layout i made and its parent is a viewpager.
Edit:
I did a little more breakpoints and debugging and from the looks of it the grid effectively remove the view from its child list (debug) but the child view keeps a reference to that same grid in its mParent variable (debug). How is this possible
EDIT:
In activity:
Button button = new Button(mContext);
button.setOnClickListener(mClickListener);
(...)
Random random = new Random();
button.setText(random.nextInt(9999) + " ");
mCurrentGridLayout.addCustomView(button);
In CustomGridLayout viewgroup class:
public void addCustomView(View view){
if((ViewGroup)view.getParent() != null){
((ViewGroup)view.getParent()).removeView(view);
}
addView(view);
}
I had that same issue when trying to create a custom banner. I believe it's because of animation during layout, that's why a delay could work. In my case, I made a custom viewgroup class to eliminate the animation delay:
private class BannerLayout extends LinearLayout {
public BannerLayout(Context context) {
super(context);
}
#Override
protected void removeDetachedView(View child, boolean animate) {
super.removeDetachedView(child, false);
}
}
Once I did this, everything worked as expected.
Hope it helps!
I had the same problem, and the answer from Iree really helped me. The cause was the animation for the layout transition, but if i set it its value null i will lose my transition animation. So what i did is add a layout transition listener, that way you can listener when the transition is done, and then add the view to its new parent.
Using Java
LayoutTransition layoutTransition = ((ViewGroup)view.getParent()).getLayoutTransition();
layoutTransition.addTransitionListener(new TransitionListener(){
#Override
public void startTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {
}
#Override
public void endTransition(LayoutTransition transition, ViewGroup container, View view, int transitionType) {
// now you can add the same view to another parent
addView(view);
}
});
Using Kotlin
val layoutTransition = (view.parent as ViewGroup).layoutTransition
layoutTransition.addTransitionListener(object : LayoutTransition.TransitionListener {
override fun startTransition(transition: LayoutTransition?,container: ViewGroup?,view: View?,transitionType: Int) {
}
override fun endTransition(transition: LayoutTransition?,container: ViewGroup?,view: View?,transitionType: Int) {
// now you can add the same view to another parent
addView(view)
}
})
In case you have to do with viewGroups that have layoutTransition or not you can do something like this:
/**
* When we don't have [LayoutTransition] onEnd is called directly
* Or
* function [onEnd] will be called on endTransition and when
* the parent is the same as container and view parent is null,
* and will remove also the transition listener
*/
private fun doOnParentRemoved(parent: ViewGroup, onEnd: () -> Unit) {
val layoutTransition = parent.layoutTransition
if (layoutTransition == null) {
onEnd.invoke()
return
}
val weakListener = WeakReference(onEnd)
layoutTransition.addTransitionListener(object : LayoutTransition.TransitionListener {
override fun startTransition(
transition: LayoutTransition?,
container: ViewGroup?,
view: View?,
transitionType: Int
) {
}
override fun endTransition(
transition: LayoutTransition?,
container: ViewGroup?,
view: View?,
transitionType: Int
) {
transition?.removeTransitionListener(this)
weakListener.get()?.invoke()
}
})
}
This is how you can use it:
sourceLayout.removeView(textView)
doOnParentRemoved(sourceLayout) {
// do your stuff when view has no parent
// add more logic to check is your view who called it in case of multiple views
}
I would suggest to double check your implementation as it can happen sometimes endTransition is not guaranteed to be called or animations can stop in middle. In my case I have used it in drag drop actions
I would like to perform some task after the creation of the graphic interface of the activity. I need to know the exact height and width of some views and change the layoutParams of some of those views based on the width and height. In the onResume method the views have all the parameters still equal to 0...
As for now I'm using a delayed task that runs after some time from the onCreate but this isn't a good solution at all...
What is the last method called in the activity creation? And are the views' width and height available in such method?
Call this inside of the onCreate()
final View rootView = getWindow().getDecorView().getRootView();
rootView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
//by now all views will be displayed with correct values
}
});
onResume() is last, but perhaps better is onViewCreated(). Its advantage is that it is not invoked every time you regain focus. But try getting properties of your view inside of post() over layout element which you need. For example:
textView.post(new Runnable() {
#Override
public void run() {
// do something with textView
}
});
The last method that runs when activity starts is onResume().
You can find it at Activity lifecycle.
If that is not good enough for you, run delayed task from this onResume() and you'll be fine.
In the last line of the onResume() method get all the data you want. It should show you all that you need.
Use a Coroutine:
In onCreate() ...
CoroutineScope(SupervisorJob()).launch {
getImageAttributes()
}
... then use a while loop to wait until image is in View ...
private fun getImageAttributes() {
while (imageView.height == 0) { /* */ }
val h = imageView.height
val w = imageView.width
val b = imageView.clipBounds
val x = imageView.x
val y = imageView.y
val tx = imageView.translationX
val ty = imageView.translationY
}
You should add a timeout or make the Job cancellable if there is a chance that the imageView.height is going to be 0.