如何使用数据绑定在ScrollView上滚动到指定位置?

3

我在我的Android应用程序中使用数据绑定,但有一个问题没有人能回答我...

如果我的ScrollView包含一些 TextInputLayout ,其中包含 InputditText 元素,如何使用数据绑定滚动到特定的textinputlayout? 现在我使用Butterknife,绑定滚动视图,并必须通过手动方式滚动到该视图的该位置,但我想知道是否有其他方法可以做到这一点。

有人有想法吗?


1
也许不是你正在寻找的完全不同的方法。但我认为你至少可以通过使用绑定器的字段来摆脱butterknife: binding.myscroller.scrollTo (如果你在这里将视图的id设置为R.id.myscroller) - Till - Appviewer.io
是的@Till,你绝对是正确的。经过更多的研究,我得到了这样一个事实,我可以像那样获得一个绑定的视图!;) - Thomas Cirksena
1个回答

2

我编写了一个小型的自定义BindingAdapter,它可以滚动到包含视图ID的变量所定义的位置。 我知道它包含一个findViewById,但对我来说这没问题。

@BindingAdapter("scrollTo")
public static void scrollTo(ScrollView view, int viewId) {

    if (viewId == 0) {
        view.scrollTo(0, 0);
        return;
    }

    View v = view.findViewById(viewId);
    view.scrollTo(0, v.getTop());
    v.requestFocus();
}

由于使用数据绑定,我可以轻松地在我的xml中添加此适配器:
<?xml version="1.0" encoding="utf-8"?>
<layout>
    <data>
        <variable
            name="viewModel"
            type="com.grumpyshoe.myapp.features.dashboard.viewmodel.DashboardViewmodel"/>
    </data>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:id="@+id/root_dashboard"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@android:color/transparent"
              android:focusable="true"
              android:focusableInTouchMode="true"
              android:orientation="vertical">

        <ScrollView
            android:id="@+id/bank_account_scroll_wrapper"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            app:scrollTo="@{viewModel.focusedViewId}"> 

        [...]
    </LinearLayout>
</layout>

不要忽略方法声明中的 static 关键字。在 @grumpyshoe 的回答中,我也曾经忽略了它。 - tir38
如果我无法将ScrollView作为参数传递,那么如何调用scrollTo函数? - Antonios Tsimourtos
@AntonisTsimourtos,我不明白为什么你不能将ScrollView作为参数传递!? 你编写的任何BindingAdapter都将有自己的视图作为第一个参数,第二个参数是你传入的参数。 你能否更详细地解释一下或者给出一个小例子,说明你想在哪里使用它? - Thomas Cirksena
对不起,这是我的错。我不得不重新构建项目,因为它通过findViewBy找不到ScrollView。 - Antonios Tsimourtos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接