2017-03-20 26 views
0

我想在ViewModel中布爾值的值發生變化時爲視圖寬度設置動畫...但我不知道如何綁定這個。使用Google Databinding動畫視圖寬度

我有這樣的看法:

<EditText 
    android:id="@+id/help_search_et" 
    android:layout_width="48dp" 
    android:layout_height="match_parent" 
    android:background="@drawable/border_search_help_txt" 
    android:hint="@string/hint_how_can_we_help" 
    android:singleLine="true" /> 

和一個視圖模型:

public class SomethingViewModel extends BaseViewModel { 
    private boolean isSearchEnabled; 

    void handleSearchRequest(){ 
     if(isSearchEnabled) { 
      isSearchEnabled = false; 

      /* I need to make the EditText expand */ 

     } else { 
      isSearchEnabled = true; 

      /* I need to make the EditText colapse */ 
     } 
    } 

} 

由於我使用MVVM,我不能有視圖的參考...所以我不能在視圖中觸發一個動畫,我需要Databinding來爲我做這個......但是我不知道如何在我看來觸發這個動畫。

我不需要寬度動畫的幫助,只需要數據綁定部分。

回答

3

有幾種方法可以做到這一點。想到的第一種方法是使用轉換:

binding.addOnRebindCallback(new OnRebindCallback() { 
    @Override 
    public boolean onPreBind(ViewDataBinding binding) { 
     TransitionManager.beginDelayedTransition(
       (ViewGroup)binding.getRoot()); 
     return super.onPreBind(binding); 
    } 
}); 

另一種方法是創建一個BindingAdapter:

@BindingAdapter("isExpanded") 
public void setExpanded(View view, boolean isExpanded) { 
    // expand or collapse View, depending on isExpanded 
} 

而且你必須將其綁定在你的佈局:

<View app:isExpanded="@{viewModel.isSearchEnabled}" .../>