KITCHEN DRINKER

主にAndroid開発メモとか

BottomSheet内のitemをscroll時にAppBarをscrollさせたくない

CoordinatorLayout + AppBarLayout + BottomSheet の組み合わせでレイアウトを組んだ際、BottomSheet内でscrollした際、AppBarLayoutの方もscrollしてしまい困ってた。

f:id:nyanyonin:20200330185537p:plain:w200
通常時
f:id:nyanyonin:20200330185533p:plain:w200
scroll時

AppBarLayoutにcustom Behavior を設定することで解決。

class BottomSheetAppBarBehavior @JvmOverloads constructor(
  context: Context?,
  attrs: AttributeSet? = null
) : AppBarLayout.Behavior(context, attrs) {
  private var mIsSheetTouched = false

  override fun onStartNestedScroll(
    parent: CoordinatorLayout,
    child: AppBarLayout,
    directTargetChild: View,
    target: View,
    nestedScrollAxes: Int,
    type: Int
  ): Boolean {
    mIsSheetTouched = target.getId() == R.id.variation_list // 優先したいBottomSheet内のscroll content id
    return (!mIsSheetTouched && super.onStartNestedScroll(
      parent, child, directTargetChild,
      target, nestedScrollAxes, type
    ))
  }

  override fun onInterceptTouchEvent(
    parent: CoordinatorLayout,
    child: AppBarLayout,
    ev: MotionEvent
  ): Boolean {
    if (ev.actionMasked == MotionEvent.ACTION_CANCEL) {
      mIsSheetTouched = false
    }
    return !mIsSheetTouched && super.onInterceptTouchEvent(parent, child, ev)
  }
}

これをAppBarLayoutに設定してあげる app:layout_behavior="jp.co.xxx.BottomSheetAppBarBehavior"