Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to position on ScrollView using databinding?

I use databinding in my android apps but there's one question no one could answer me...

If my ScrollView contains some TextInputLayout containing InputditText elements how could i scroll to a specific textinputlayout by using databinding? Nowadays I use Butterknife, binding the scrollview, and have to scroll to this position of that view via that manually but I'm wondering if there's no other way to do that.

Anybody an idea?

like image 517
Thomas Cirksena Avatar asked Apr 10 '26 01:04

Thomas Cirksena


1 Answers

I wrote a little custom BindingAdapter that scrolls to the position defined by a variable containing a view id. I know it contains a findViewById but for me that's ok.

@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();
}

Because of using databinding, I can easily add this adapter in my 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>
like image 109
Thomas Cirksena Avatar answered Apr 11 '26 14:04

Thomas Cirksena