在渲染之前触发ViewPager片段内嵌套片段的动画

时间:2017-12-21 23:33:58

标签: android android-fragments android-viewpager kotlin android-animation

我有一个ViewPager片段

class PagerFragment() : Fragment() {
  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      super.onViewCreated(view, savedInstanceState)

      val pagerView = view as ViewPager
      val adapter = PagerAdapter(childFragmentManager, items)
      pagerView.adapter = adapter
  }
}

使用以下适配器

class PagerAdapter(val fm: FragmentManager, val items: ArrayList<Item>)
    : FragmentStatePagerAdapter(fm) {

    override fun getItem(position: Int): Fragment {
        val item = items[position]
        return NestedFragment.newInstance(item)
    }

    override fun getCount(): Int {
        return  items.size
    }
}

以下列方式触发onViewCreated以几个动画嵌套片段:

class NestedFragment() : Fragment() {
  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      super.onViewCreated(view, savedInstanceState)

      val one = AnimationUtils.loadAnimation(context, R.anim.one)
      val two = AnimationUtils.loadAnimation(context, R.anim.two)
      val three = AnimationUtils.loadAnimation(context, R.anim.three)

      view.findViewById<ImageView>(R.id.pic).startAnimation(one)
      view.findViewById<ConstraintLayout>(R.id.content).startAnimation(two)
      view.findViewById<ImageView>(R.id.img).startAnimation(three)
  }
}

然而,通常在屏幕上显示嵌套片段时,动画已经开始甚至结束:(

有没有办法确定片段何时确实在设备的屏幕上呈现? 当然,欢迎任何其他有用的建议来克服这个问题。

1 个答案:

答案 0 :(得分:0)

这对我有用。

class NestedFragment() : Fragment() {
  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      super.onViewCreated(view, savedInstanceState)

      val one = AnimationUtils.loadAnimation(context, R.anim.one)
      val two = AnimationUtils.loadAnimation(context, R.anim.two)
      val three = AnimationUtils.loadAnimation(context, R.anim.three)
      view.post(Runnable {
        /* 
          If the animation doesn't trigger you may try to hide 
          elements visibility and reveal them before animation starts
        */
        view.findViewById<ImageView>(R.id.pic).startAnimation(one)
        view.findViewById<ConstraintLayout>(R.id.content).startAnimation(two)
        view.findViewById<ImageView>(R.id.img).startAnimation(three)
      })
  }
}

如果动画仍然没有触发,您可能会尝试隐藏视图可见性并在动画之前显示它们。

相关问题