Skip to content

Instantly share code, notes, and snippets.

@zzdjk6
Created June 11, 2017 12:37
Show Gist options
  • Save zzdjk6/25ab4489ba7e63707a8c9de9db56edc0 to your computer and use it in GitHub Desktop.
Save zzdjk6/25ab4489ba7e63707a8c9de9db56edc0 to your computer and use it in GitHub Desktop.
ListView+RealSmoothScroll.kt
import android.os.Handler
import android.view.View
import android.widget.AbsListView
import android.widget.AdapterView
// workaround for scrolling issue
// refer: https://stackoverflow.com/questions/11431832/android-smoothscrolltoposition-not-working-correctly
fun AbsListView.realSmoothScrollToPosition(position: Int) {
fun getChildAtPosition(view: AdapterView<*>, position: Int): View? {
val index = position - view.firstVisiblePosition
if (index >= 0 && index < view.childCount) {
return view.getChildAt(index)
} else {
return null
}
}
val child = getChildAtPosition(this, position)
// There's no need to scroll if child is already at top or view is already scrolled to its end
if (child != null && (child.top == 0 || child.top > 0 && !this.canScrollVertically(1))) {
return
}
this.setOnScrollListener(object : AbsListView.OnScrollListener {
override fun onScrollStateChanged(view: AbsListView, scrollState: Int) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
view.setOnScrollListener(null)
// Fix for scrolling bug
Handler().post { view.setSelection(position) }
}
}
override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
}
})
// Perform scrolling to position
Handler().post { this.smoothScrollToPositionFromTop(position, 0) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment