【问题标题】:Does View gets redrawn when property programatically changed to same value?当属性以编程方式更改为相同值时,视图是否会重绘?
【发布时间】:2022-01-05 19:06:35
【问题描述】:

让我们在片段中有一些视图(例如 LinearLayout 或 ImageView)。如果我以编程方式将此视图的属性(例如更改背景颜色)更改为已设置的相同属性,是否会重绘/重新渲染视图?

双组示例:

binding.someLinearLayout.setBackgroundColor(redColor)
binding.someLinearLayout.setBackgroundColor(grayColor);
binding.someLinearLayout.setBackgroundColor(grayColor);
binding.someLinearLayout.setBackgroundColor(grayColor);

LinearLayout 会重绘两次还是四次?如果 4 次,我应该实施这样的事情来防止它吗?

fun setBackgroundColor(ll: LinearLayout, color: Int){
   val current = binding.progressBarChunk4.background as ColorDrawable
   if(current.getColor() != color)
      ll.setBackgroundColor(color)
}

setBackgroundColor(binding.someLinearLayout, redColor); // Color set
setBackgroundColor(binding.someLinearLayout, grayColor); // Color set
setBackgroundColor(binding.someLinearLayout, grayColor); // ignored
setBackgroundColor(binding.someLinearLayout, grayColor); // ignored

所以基本上我问的是多组相同的属性是否会影响性能,因为每次都会重绘视图。

【问题讨论】:

    标签: android kotlin android-drawable


    【解决方案1】:

    如果您像这样连续四次调用setBackgroundColor,则不会导致四次重绘。在当前函数返回后,视图只会在主线程的下一个循环中重绘一次。

    更改这些属性通常会使视图无效,因此您第一次调用setBackgroundColor 将触发主线程的下一个循环重绘,即使它与现有颜色匹配。我不能保证核心视图中的每个现有属性都是如此,因为我还没有检查它们。 setBackgroundColorsetText 绝对是这样。

    您对当前颜色的防御性检查可能会防止不必要的重绘,但前提是您最终不会在主线程的此迭代中改变任何视图。我想不出值得担心的情况。如果这是在onCreate()onViewCreated() 中,则无论如何还没有绘制视图。如果这是在单击侦听器中,则无论如何您的视图都会重新绘制,因为您的按钮的视觉状态正在发生变化。

    可能值得对影响视图大小的更改进行防御性检查,因为这样您可能会阻止重新布局。但可能只有在某些动画期间发生这种情况,否则节省的费用不会很明显。

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 1970-01-01
      • 2019-09-20
      • 1970-01-01
      • 2013-03-09
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 2017-02-27
      相关资源
      最近更新 更多