【发布时间】:2018-12-20 22:31:22
【问题描述】:
我有一个 NestedScrollView 与 CoordinatorLayout + AppBarLayout + CollapsingToolbarLayout 一起使用,视差效果类似于this tutorial
我需要以编程方式滚动内容(最好是平滑滚动,即动画),但是调用滚动方法(scrollBy()、scrollTo()、smoothScrollTo()、smoothScrollBy())什么都不做。
请注意,我使用的是app:layout_behavior="@string/appbar_scrolling_view_behavior"
当用户单击按钮时,我在 Kotlin 中调用 nsv_form.smoothScrollBy(0, 300),但没有任何反应:(
(也试过scrollTo(),scrollBy(),+- 300,各种不同的变体)
更新:我研究了源代码,似乎*scroll*() 方法期望布局的内容大于父视图(有道理)。就我而言,内容较小,所以我怀疑这就是滚动方法不起作用的原因。也许我需要不同的东西而不是scroll?
NestedScrollView 的位置部分从屏幕开始,其上方的图像位于 CollapsingToolbarLayout,like this,因此我似乎需要以编程方式移动 NestedScrollView 的位置并触发 CoordinatorLayout 的滚动行为。 -- 我该怎么做?
这是我的布局:
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/transparent">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="@+id/iv_image"
android:layout_width="match_parent"
android:layout_height="@dimen/image_height"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax"
tools:src="@drawable/some_image" />
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="@+id/nsv_form"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
android:orientation="vertical">
[... child views...]
</LinearLayout>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
TLDR:如何以编程方式滚动like this?
【问题讨论】:
-
如果您只有一个子视图,我认为您应该使用滚动视图,因为您的案例中只有一个子布局,即 LinearLayout。
-
@SumitShukla 我尝试用 ScrollView 切换 NestedScrollView,它打破了视差滚动行为(布局根本不滚动)
标签: android android-coordinatorlayout android-nestedscrollview