Created
June 11, 2017 12:37
-
-
Save zzdjk6/25ab4489ba7e63707a8c9de9db56edc0 to your computer and use it in GitHub Desktop.
ListView+RealSmoothScroll.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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