如何避免在打印机上检查大量图像以减少延迟?我想在不丢失检查功能的情况下尽快使 TextView1
变为绿色。
TextView1.setOnClickListener {
if (image_view.drawable.constantState == ContextCompat.getDrawable(
this,
R.drawable.cat__1_
)?.constantState ||
image_view.drawable.constantState == ContextCompat.getDrawable(
this,
R.drawable.cat__2_
)?.constantState ||
image_view.drawable.constantState == ContextCompat.getDrawable(
this,
R.drawable.cat__3_
)?.constantState ||
image_view.drawable.constantState == ContextCompat.getDrawable(
this,
R.drawable.cat__4_
)?.constantState
) {
TextView1.setBackgroundResource(R.color.green);
Handler().postDelayed({
TextView1.setBackgroundResource(R.color.white)
}, 50)
}
编辑:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
showGreen = false
TextView1.setOnClickListener {
showGreen = isGreenBackgroundShouldAppear()
}
}
fun isGreenBackgroundShouldAppear(): Boolean {
return image_view.drawable.constantState == ContextCompat.getDrawable(
this,
R.drawable.cat__1_
)?.constantState ||
image_view.drawable.constantState == ContextCompat.getDrawable(
this,
R.drawable.cat__2_
)?.constantState ||
image_view.drawable.constantState == ContextCompat.getDrawable(
this,
R.drawable.cat__3_
)?.constantState ||
image_view.drawable.constantState == ContextCompat.getDrawable(
this,
R.drawable.cat__4_
)?.constantState
// Do the checking here
// and set the showGreen variable
}
最佳答案
我建议预先计算加载到 image_view.drawable
中的可绘制对象的状态,并在点击监听器中检查状态值以加载必要的资源。
我不确定您在哪里加载此图像,但是,如果这是一个 Activity ,请在您 Activity 的 onCreate
函数中按如下方式进行预计算。
public boolean showGreen = false;
public void onCreate() {
showGreen = isGreenBackgroundShouldAppear();
}
public boolean isGreenBackgroundShouldAppear() {
// Do the checking here
// and set the showGreen variable
}
然后在 TextView1
的 onClickListener
中,读取 showGreen
的值并自动分配背景。
如果在此期间更新了可绘制图像,您需要确保每次调用 isGreenBackgroundShouldAppear
函数以将正确的值加载到 showGreen
变量。
请注意,我只是提供了一些 Java 伪代码。我希望这有助于解决您的问题。
更新:您可以尝试这样的操作。
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
showGreen = isGreenBackgroundShouldAppear()
TextView1.setOnClickListener {
if (showGreen) {
// Set the green background here
} else {
// Set the other background
}
}
}
关于android - 检查 setOnClickListener() 上的图像以减少 View 延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507165/