ViewPager片段中的嵌套片段的动画之前触发渲染(Animation of nested fra

2019-10-30 04:22发布

我有一个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)
  }
}

然而往往由当时的嵌套片段显示动画已经开始或结束,甚至在屏幕上:(

有没有一种方法,以确定何时片段的确是该设备的屏幕上呈现? 当然,任何其他有用的建议,以解决这一问题亦欢迎。

Answer 1:

下面是我工作。

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)
      })
  }
}

如果动画仍然不会触发您可以尝试隐藏视图的知名度和动画之前正确的显示它们。



文章来源: Animation of nested fragment within ViewPager fragment is triggered before render