gpt4 book ai didi

android - 获取用于测试的 android View 的背景色调

转载 作者:行者123 更新时间:2023-12-04 17:31:16 26 4
gpt4 key购买 nike

我正在使用 Espresso 创建 Android Instrumented 测试,我想测试 View 的 backgroundTint 在特定操作后是否发生变化。我没有运气找到专门针对背景色调的类似问题。在这种情况下,它是一个使用圆形可绘制对象的 ImageView,并且颜色根据服务器连接从绿色变为红色。 View 正在通过 livedata 数据绑定(bind)更新

<ImageView
android:id="@+id/connected_status"
android:layout_width="10dp"
android:layout_height="10dp"
android:layout_gravity="end|top"
android:background="@drawable/circle"
android:backgroundTint="@{safeUnbox(viewModel.onlineStatus) ? @colorStateList/colorGreenMaterial : @colorStateList/colorRedPrimary}"
android:contentDescription="@string/connection_indication"
/>

如何在 Instrumented 测试期间以编程方式获取 ImageView 的 backgroundTint 并检查其颜色?

最佳答案

我相信随着测试的进行,我找到了解决这个问题的方法,但是我不知道这是否是最好的解决方法。我注意到从 ImageView 获取 backgroundTintList 时它包含一个表示颜色的整数数组。我能够像这样使用它来测试颜色 (Kotlin):

// Get the integer value of the colors to test
val redColorInt = Color.parseColor(activityTestRule.activity.getString(R.color.colorRedPrimary))
var greenColorInt = Color.parseColor(activityTestRule.activity.getString(R.color.colorGreenMaterial))

// Add integers to a stateSet array
val stateSet = intArrayOf(redColorInt, greenColorInt)

// Get the view
val connectedStatus = activityTestRule.activity.findViewById<ImageView>(id.connected_status)

// Get the backgroundTintList
var tintList = connectedStatus.backgroundTintList

// Assert color, getColorForState returns 1 as default to fail the test if the correct color is not found
assertThat(tintList!!.getColorForState(stateSet, 1), `is`(redColorInt))

//Perform actions that change the background tint
...

// Get the updated backgroundTintList
tintList = connectedStatus.backgroundTintList

// Assert new color is now set
assertThat(tintList!!.getColorForState(stateSet, 1), `is`(greenColorInt))

关于android - 获取用于测试的 android View 的背景色调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59470752/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com