列表视图滚动时如何隐藏BottomNavigationView

时间:2018-08-15 14:12:40

标签: android bottomnavigationview

我已经使用BottomNavigationView创建了一个应用程序,但是我希望当用户滚动列表视图时,BottomNavigationView应该隐藏。我做了很多尝试,但是我做不到。谁能帮我吗?

布局代码:

<android.support.design.widget.BottomNavigationView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/bottom_nav_menu"/>

1 个答案:

答案 0 :(得分:0)

您必须创建一个类来处理BottomNavigationView的行为。

下面,我显示用科特林制作的代码。

class BottomNavigationBehavior constructor(
    context: Context,
    attrs: AttributeSet? = null
) : CoordinatorLayout.Behavior<BottomNavigationView>(context, attrs) {

  override fun layoutDependsOn(
      parent: CoordinatorLayout,
      child: BottomNavigationView,
      dependency: View
  ): Boolean {
    return dependency is FrameLayout
  }

  override fun onStartNestedScroll(
      coordinatorLayout: CoordinatorLayout,
      child: BottomNavigationView,
      directTargetChild: View,
      target: View,
      axes: Int,
      type: Int
  ): Boolean {
    return axes == ViewCompat.SCROLL_AXIS_VERTICAL
  }
/*this is where bottomnavigation is shown or hidden*/
  override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, child: BottomNavigationView,
      target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) {
    if (dy < 0) {
      showBottomNavigationView(child)
    } else if (dy > 0) {
      hideBottomNavigationView(child)
    }
  }

  private fun hideBottomNavigationView(view: BottomNavigationView) {
    view.animate().translationY(view.height.toFloat())
  }

  private fun showBottomNavigationView(view: BottomNavigationView) {
    view.animate().translationY(0f)
  }
}

创建类之后,我们需要告诉BottomNavigationView哪个类将控制其行为。

val layoutParams: CoordinatorLayout.LayoutParams = mBottomNavigation.layoutParams as CoordinatorLayout.LayoutParams
    layoutParams.behavior = BottomNavigationBehavior(this)

希望对您有帮助。