我在我的项目中使用具有自定义行为的CoordinatorLayout和NestedScrollView。除了一个问题,它运作良好。当我调用nestedScrollView.smoothScrollTo(0,0)时,我在MyCustomBehavior中得到了错误的Y坐标。当我用手指滚动时,我会收到正确的坐标。通过smoothScrollTo()方法滚动时如何在行为类中获取正确的坐标?
这是我的代码:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="300dp"
android:layout_height="150dp"
android:background="#f00"
android:layout_gravity="center_horizontal"
app:layout_behavior="com.mysite.app.MyCustomBehavior" />
<com.mysite.app.CustomScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Very long text here" />
</com.mysite.app.CustomScrollView>
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_marginTop="24dp"
android:elevation="20dp" />
</android.support.design.widget.CoordinatorLayout>
</android.support.constraint.ConstraintLayout>
CustomScrollView:
class CustomScrollView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : NestedScrollView(context, attrs, defStyleAttr) {
private val runnable = Runnable {
if (scrollY in 1..299) {
smoothScrollTo(0,0)
}
}
override fun stopNestedScroll(type: Int) {
super.stopNestedScroll(type)
removeCallbacks(runnable)
handler.postDelayed(runnable, 200)
}
}
行为:
class CollapsingImageBehavior(private val context: Context, attrs: AttributeSet?) : CoordinatorLayout.Behavior<CardView>(context, attrs) {
private var scroll = 0
override fun layoutDependsOn(parent: CoordinatorLayout, child: CardView, dependency: View): Boolean {
return dependency is NestedScrollView
}
override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: CardView, directTargetChild: View, target: View, axes: Int, type: Int): Boolean {
return axes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type)
}
override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: CardView, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type)
scroll += dyConsumed
Log.d("tag", "onNestedScroll " + scroll)
}
override fun onDependentViewChanged(parent: CoordinatorLayout, child: CardView, dependency: View): Boolean {
return true
}
}