Android拖动动画并调整片段大小

时间:2019-01-26 19:16:03

标签: android android-animation

我有一个(a >= 10 and b>= 10 and c>=10) OR (a >= 10 and d>=10 and e >= 10),其中有一个Activity和其他Fragment。显示Views时,它将显示为全屏(Fragment)。我正在寻找的行为是将match_parent向下拖动以将其最小化,因此它在Fragment顶部以100dp高度的浮动视图显示(请检查YouTube播放器动画是否为参考)。

此外,子视图是否需要更改位置取决于Activity是全屏还是浮动迷你状态

由于我对高级视图动画几乎没有经验。很想获得一些有关如何实现此目标的参考或代码示例。

目前,我正在尝试使用FragmentGestureDetectorCompat来实现这一点。

1 个答案:

答案 0 :(得分:3)

您需要使用CoordinatorLayout和BottomSheetBehavior。

使用CoordinatorLayout作为活动容器,并将BottomSheetBehavior添加到片段容器中

活动代码示例:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

     <FrameLayout
        android:id="@+id/your_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="android.support.design.widget.BottomSheetBehavior" />

</android.support.design.widget.CoordinatorLayout>

使用FragmentManager从活动中打开下一个片段:

supportFragmentManager.beginTransaction().add(R.id.your_fragment_container, YourFragment(), null).commitAllowingStateLoss()

接下来添加到片段代码:

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    // get behavior from fragment container
    val behavior = BottomSheetBehavior.from(view.parent as ViewGroup)!! 
    // listen change behavior state for change position of child views
    behavior.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
        override fun onStateChanged(bottomSheet: View, newState: Int) {
            changeHeaderState(newState)
        }

        override fun onSlide(bottomSheet: View, slideOffset: Float) {

        }
    })
    behavior.apply {
        // init state
        state = STATE_COLLAPSED
        // doesn't hide your fragment on swipe down
        isHideable = false
        // height of the bottom sheet when it is collapsed.
        peekHeight = view.resources.getDimensionPixelSize(R.id.floating_view_100dp)
    }
    onCollapsed()
}

private fun changeHeaderState(newState: Int) {
    when (newState) {
        STATE_COLLAPSED -> onCollapsed()
        STATE_EXPANDED -> onExpanded()
    }
}

private fun onCollapsed() {
    // animate on collapse
}

private fun onExpanded() {
    // animate on expand
}