简体   繁体   中英

How to bind a viewmodel to a bottomsheet

I am trying to figure out how to bind a viewmodel to a bottomsheet in a way that I can have the bottomsheet both expand, collapse, and hide using observable fields on the viewmodel.

Thank you!

You should use custom BindingAdapter .

@BindingAdapter("bottomSheetBehaviorState")
public static void setState(View v, int bottomSheetBehaviorState) {
    BottomSheetBehavior<View> viewBottomSheetBehavior = BottomSheetBehavior.from(v);
    viewBottomSheetBehavior.setState(bottomSheetBehaviorState);
}

Bind it in xml to your view:

<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>

And change state in ViewModel. Related code from my 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM