【问题标题】:Is there a way to specify TypedValue in ObjectAnimator for textSize?有没有办法在 ObjectAnimator 中为 textSize 指定 TypedValue?
【发布时间】:2019-05-14 20:26:00
【问题描述】:

我有一个 TextView,我想为它的 textSize 设置动画。这是使用 ObjectAnimator 为 textSize 设置动画的代码。

    val newSize = resources.getDimension(R.dimen.selected_text_size)
    val animator = ObjectAnimator.ofFloat(tv_text, "textSize", newSize)
    animator.duration = 200
    animator.start()

问题在于resources.getDimension(R.dimen.selected_text_size)返回一个以像素为单位的文本大小值,并且似乎 ObjectAnimator 默认使用 sp 值,这使得最终的动画大小比预期大得多

如果我改变了

val newSize = resources.getDimension(R.dimen.selected_text_size)

val newSize = resources.getDimension(R.dimen.selected_text_size) / (resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)

然后,它将给出正确的最终动画尺寸,因为第二个将获得 sp 值而不是像素值。

如果我在没有动画的情况下更改 textSize,我可以像这样指定 TypedValue:

tv_text.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.selected_text_size))

那么,有没有办法在使用 ObjectAnimatortextSize 设置动画时指定 TypedValue

【问题讨论】:

    标签: android textview objectanimator


    【解决方案1】:

    据我所知,你不能直接这样做。但是你可以继承TextView并添加一个方法“setTextSizePixel”

    fun setTextSizePixel(size: Float) {
        setTextSize(TypedValue.COMPLEX_UNIT_PX, size)
    }
    

    然后用 MyTextView 替换 TextView 需要 px 文本大小的动画 并使用 ObjectAnimator 为 MyTextView 的 textSizePixel 属性设置动画:

    ObjectAnimator.ofFloat(myTextView, "textSizePixel", oldSizePx, newSizePx)
           .apply {
                duration = 3000
                start()
           }
    

    或者使用 ObjectAnimator 的父类 ValueAnimator 通过在一个地方添加代码来实现:

    ValueAnimator.ofFloat(oldSizePx, newSizePx).apply {
         addUpdateListener { updatedAnimation ->
             tv_text.setTextSize(TypedValue.COMPLEX_UNIT_PX, updatedAnimation.animatedValue as Float)
         }
         duration = 3000
         start()
    }
    

    【讨论】:

      猜你喜欢
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多