UI android 中的线程更改
UI changes in a thread in android
我正在编写一个 android 应用程序,它要求我在再次更改图像按钮之前将其前景保持一秒钟。所以我写了下面的代码(它用于更改其他项目中两个按钮上文本的颜色)并且我知道问题是我正在更改非主线程中的 UI 元素并且我知道我不能使用“runOnUiThread”方法,但无法在我当前的函数中找到这样做的方法,所以如果有人能帮助我,我将不胜感激。
public void waitTime(ImageButton imageButton1, ImageButton imageButton2) {
HandlerThread handlerThread = new HandlerThread("showText");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
Runnable runnable = () -> {
imageButton1.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
imageButton2.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
};
handler.postDelayed(runnable, 1000);
}
可以使用View的postDelayed
方法:
Runnable runnable = () -> {
imageButton1.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
imageButton2.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
};
imageButton1.postDelayed(runnable, 1000);
它将在主线程中更新 UI。
我正在编写一个 android 应用程序,它要求我在再次更改图像按钮之前将其前景保持一秒钟。所以我写了下面的代码(它用于更改其他项目中两个按钮上文本的颜色)并且我知道问题是我正在更改非主线程中的 UI 元素并且我知道我不能使用“runOnUiThread”方法,但无法在我当前的函数中找到这样做的方法,所以如果有人能帮助我,我将不胜感激。
public void waitTime(ImageButton imageButton1, ImageButton imageButton2) {
HandlerThread handlerThread = new HandlerThread("showText");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
Runnable runnable = () -> {
imageButton1.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
imageButton2.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
};
handler.postDelayed(runnable, 1000);
}
可以使用View的postDelayed
方法:
Runnable runnable = () -> {
imageButton1.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
imageButton2.setForeground(AppCompatResources.getDrawable(this, R.color.teal_200));
};
imageButton1.postDelayed(runnable, 1000);
它将在主线程中更新 UI。