From 4496f82d5b5a6e9688b0a1d0389ac5733d61eb40 Mon Sep 17 00:00:00 2001 From: Viktor De Pasquale Date: Thu, 2 May 2019 16:23:20 +0200 Subject: [PATCH] Added scrolling to latest items while flashing Since the adapter might be set _after_ the request, as there is no guaranteed order, it's done with waiting recursion yuck --- .../magisk/utils/DataBindingAdapters.kt | 38 +++++++++++++++++++ app/src/main/res/layout/activity_flash.xml | 2 + 2 files changed, 40 insertions(+) diff --git a/app/src/main/java/com/topjohnwu/magisk/utils/DataBindingAdapters.kt b/app/src/main/java/com/topjohnwu/magisk/utils/DataBindingAdapters.kt index d6cc4d32f..cf3848e63 100644 --- a/app/src/main/java/com/topjohnwu/magisk/utils/DataBindingAdapters.kt +++ b/app/src/main/java/com/topjohnwu/magisk/utils/DataBindingAdapters.kt @@ -13,6 +13,7 @@ import androidx.databinding.InverseBindingAdapter import androidx.databinding.InverseBindingListener import androidx.drawerlayout.widget.DrawerLayout import androidx.interpolator.view.animation.FastOutSlowInInterpolator +import androidx.recyclerview.widget.RecyclerView import androidx.viewpager.widget.ViewPager import com.google.android.material.navigation.NavigationView import com.skoumal.teanity.extensions.subscribeK @@ -141,4 +142,41 @@ fun setSelectedItemPositionListener(view: Spinner, listener: InverseBindingListe @BindingAdapter("onTouch") fun setOnTouchListener(view: View, listener: View.OnTouchListener) { view.setOnTouchListener(listener) +} + +@BindingAdapter("scrollToLast") +fun setScrollToLast(view: RecyclerView, shouldScrollToLast: Boolean) { + + fun scrollToLast() = view.post { + view.scrollToPosition(view.adapter?.itemCount?.minus(1) ?: 0) + } + + fun wait(callback: () -> Unit) { + Observable.timer(1, TimeUnit.SECONDS).subscribeK { callback() } + } + + val tag = RecyclerView::class.java.name.sumBy { it.toInt() } + + fun RecyclerView.Adapter<*>.setListener() { + val observer = object : RecyclerView.AdapterDataObserver() { + override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { + scrollToLast() + } + } + registerAdapterDataObserver(observer) + view.setTag(tag, observer) + } + + fun RecyclerView.Adapter<*>.removeListener() { + val observer = view.getTag(tag) as? RecyclerView.AdapterDataObserver ?: return + unregisterAdapterDataObserver(observer) + } + + fun trySetListener(): Unit = view.adapter?.setListener() ?: wait { trySetListener() } + + if (shouldScrollToLast) { + trySetListener() + } else { + view.adapter?.removeListener() + } } \ No newline at end of file diff --git a/app/src/main/res/layout/activity_flash.xml b/app/src/main/res/layout/activity_flash.xml index 7d650b8af..81dc153f7 100644 --- a/app/src/main/res/layout/activity_flash.xml +++ b/app/src/main/res/layout/activity_flash.xml @@ -96,9 +96,11 @@