[英]UI changes in a thread in android
我正在編寫一個 android 應用程序,該應用程序要求我在再次更改之前按住圖像按鈕的前景一秒鍾。 所以我寫了下面的代碼(它可以在其他項目的兩個按鈕上更改文本的 colors)並且我知道問題是我正在更改非主線程中的 UI 元素並且我知道我不能使用“runOnUiThread”方法,但在我目前的 function 中找不到這樣做的方法,所以如果有人可以幫助我,請感謝。
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.