如何将视图模型绑定到底部表
How to bind a viewmodel to a bottomsheet
我想弄清楚如何将视图模型绑定到底部表,这样我就可以使用视图模型上的可观察字段使底部表展开、折叠和隐藏。
谢谢!
您应该使用自定义 BindingAdapter
。
@BindingAdapter("bottomSheetBehaviorState")
public static void setState(View v, int bottomSheetBehaviorState) {
BottomSheetBehavior<View> viewBottomSheetBehavior = BottomSheetBehavior.from(v);
viewBottomSheetBehavior.setState(bottomSheetBehaviorState);
}
在 xml 中将其绑定到您的视图:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
(...)
<android.support.v4.widget.NestedScrollView
android:id="@+id/group_bottom_sheet"
bottomSheetBehaviorState="@{viewModel.bottomSheetBehaviorState}"
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="@android:color/holo_blue_bright"
app:behavior_hideable="true"
app:behavior_peekHeight="50dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"/>
(...)
</layout>
并更改 ViewModel 中的状态。我的 ViewModel 中的相关代码:
public final ObservableInt bottomSheetBehaviorState = new ObservableInt(BottomSheetBehavior.STATE_HIDDEN);
@Override
public void onAction(boolean show){
bottomSheetBehaviorState.set(show? BottomSheetBehavior.STATE_COLLAPSED : BottomSheetBehavior.STATE_HIDDEN);
}
我想弄清楚如何将视图模型绑定到底部表,这样我就可以使用视图模型上的可观察字段使底部表展开、折叠和隐藏。
谢谢!
您应该使用自定义 BindingAdapter
。
@BindingAdapter("bottomSheetBehaviorState")
public static void setState(View v, int bottomSheetBehaviorState) {
BottomSheetBehavior<View> viewBottomSheetBehavior = BottomSheetBehavior.from(v);
viewBottomSheetBehavior.setState(bottomSheetBehaviorState);
}
在 xml 中将其绑定到您的视图:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
(...)
<android.support.v4.widget.NestedScrollView
android:id="@+id/group_bottom_sheet"
bottomSheetBehaviorState="@{viewModel.bottomSheetBehaviorState}"
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="@android:color/holo_blue_bright"
app:behavior_hideable="true"
app:behavior_peekHeight="50dp"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"/>
(...)
</layout>
并更改 ViewModel 中的状态。我的 ViewModel 中的相关代码:
public final ObservableInt bottomSheetBehaviorState = new ObservableInt(BottomSheetBehavior.STATE_HIDDEN);
@Override
public void onAction(boolean show){
bottomSheetBehaviorState.set(show? BottomSheetBehavior.STATE_COLLAPSED : BottomSheetBehavior.STATE_HIDDEN);
}