개발일지

Android in A..Z - CoordinatorLayout (Behavior / Event) 본문

Android (안드로이드)/CoordinatorLayout

Android in A..Z - CoordinatorLayout (Behavior / Event)

강태종 2021. 1. 27. 01:52


CollapsingToolbarLayout이 CollapseMode인지 아닌지 Handling하기

binding.nestedScrollView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
    if (scrollY >= binding.toolbar.height && oldScrollY < binding.toolbar.height) {
        Log.d("COORDINATOR", "COLLAPSED")
    } else if (scrollY < binding.toolbar.height && oldScrollY >= binding.toolbar.height){
        Log.d("COORDINATOR", "EXPANDED")
    }
}

FloatingActionButton Scroll 내리면 숨기고 올리면 보이게하기

FloatingActionButton의 Behavior를 상속받아서 override하고 Behavior를 설정한다. 이 때 CoordinatorLayout은 View의 Visible이 GONE인 View의 Behavior를 수신하지도 않고 전파하지도 않는 점을 주의해야한다.

class FloatingActionButtonScrollBehavior(context: Context? = null, attrs: AttributeSet? = null) : FloatingActionButton.Behavior(context, attrs) {
    override fun onStartNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, directTargetChild: View, target: View, axes: Int, type: Int): Boolean {
        return axes == ViewCompat.SCROLL_AXIS_VERTICAL || super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type)
    }

    override fun onNestedScroll(coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int, consumed: IntArray) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, consumed)
        if (dyConsumed > 0) {
            child.hide(object : FloatingActionButton.OnVisibilityChangedListener() {
                override fun onHidden(fab: FloatingActionButton) {
                    super.onHidden(fab)
                    fab.visibility = View.INVISIBLE
                }
            })
        } else if (dyConsumed < 0) {
            child.show()
        }
    }
}
        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fab"
            app:layout_behavior="com.taetae98.coordinatorlayout.FloatingActionButtonScrollBehavior"
            app:tint="@color/white"
            app:backgroundTint="@color/red"
            app:layout_anchor="@id/recyclerView"
            android:layout_margin="10dp"
            android:onClick="@{onFavorite}"
            android:visibility="@{movie.favorite ? View.GONE : View.VISIBLE}"
            app:layout_anchorGravity="bottom|end"
            android:src="@drawable/ic_favorite"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

Git (예제코드)

github.com/KangTaeJong98/Example/tree/main/Android/CoordinatorLayout

 

KangTaeJong98/Example

My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.

github.com

 

Comments