检查 setOnClickListener() 上的图像以减少视图延迟

Checking for images on setOnClickListener() in view latency reduction

如何避免在印刷机上检查大量图像以减少延迟?我想通过不丢失检查功能来尽快使 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
}

然后在 TextView1onClickListener 中,读取 showGreen 的值并自动分配背景。

如果图像drawable在此期间更新,您需要确保每次调用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
         }
     }
}