2016-10-01 25 views
3

我使用數據綁定在我的Android應用程序,但有一個問題沒人能回答我...如何使用數據綁定滾動到ScrollView的位置?

如果我的滾動型包含一些InputditText元素我如何可以通過使用數據綁定滾動到一個特定的textinputlayout TextInputLayout? 現在我使用Butterknife,綁定scrollview,並且必須通過手動滾動到該視圖的這個位置,但是我想知道是否沒有其他方法可以做到這一點。

有人有想法嗎?

+1

可能不是完全不同的方法,你要尋找的。但我認爲你至少可以通過使用活頁夾的字段來刪除butterknife: binding.myscroller.scrollTo (如果你在此設置視圖的id爲R.id.myscroller) – Till

+0

是的,@你真是絕對正確。經過一些更多的研究後,我得到了這樣一個事實,即我可以得到一個像這樣的綁定視圖! ;) – grumpyshoe

回答

1

我寫了一個小的自定義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> 
+0

不要忽略方法聲明中的'static'。我在@ grumpyshoe的回答中掩蓋了它。 – tir38

+0

如果我無法將ScrollView作爲參數傳遞,您如何調用'scrollTo'函數? –

+0

@AntonisTsimourtos我不明白爲什麼你不能傳遞ScrollView作爲參數!? 您編寫的任何BindingAdapter將擁有它自己的視圖作爲第一個參數,第二個是您傳入的視圖。 您能解釋更多或給出一個您想要使用它的什麼或哪些地方的小例子嗎? – grumpyshoe

相關問題