我创建了一个计时器,每5秒更改一次布局颜色,但是标题中提到了错误。
我尝试使用runonuithread,handler,但似乎没有任何作用
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run()
{
colorchange();
}
});
private void colorchange() {
final Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
rl = findViewById(R.id.am);
int[] androidColors = getResources().getIntArray(R.array.androidcolors);
int randomcolor = androidColors[new Random().nextInt(androidColors.length)];
rl.setBackgroundColor(randomcolor);
}
},0,5000);
}
答案 0 :(得分:0)
您可以尝试通过这种方式进行操作:
private void colorchange() {
final Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
MyActivityName.this.runOnUiThread(new Runnable() {
@Override
public void run() {
rl = findViewById(R.id.am);
int[] androidColors = getResources().getIntArray(R.array.androidcolors);
int randomcolor = androidColors[new Random().nextInt(androidColors.length)];
rl.setBackgroundColor(randomcolor);
}
});
}
},0,5000);
}
您必须如上所述在主UI线程上运行它。看看this类似的帖子。
答案 1 :(得分:0)
我不喜欢“奔跑”,但是只有Kotlin可以避免。不过,您应该尽量不要在UI线程中加载可能会冻结它的内容,而只能依赖于真正需要的内容进行更改。这意味着诸如生成随机int
颜色之类的东西应该不在runOnUiThread
之外。
package com.example.proofofconcept;
import android.os.Bundle;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
import java.sql.Time;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ThreadLocalRandom;
public class BackgroundColorChanger extends AppCompatActivity {
private RelativeLayout relativeLayout;
private final int[] colors = {R.color.white,
R.color.colorPrimary,
R.color.colorPrimaryDark,
R.color.yellow};
private final TimerTask timerTask = new TimerTask() {
@Override
public void run() {
final int random = ThreadLocalRandom.current().nextInt(0, colors.length);
runOnUiThread(new Runnable() {
@Override
public void run() {
relativeLayout.setBackgroundResource(colors[random]);
}
});
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_background_color_changer);
findViews();
colorChanger();
}
private void findViews() {
relativeLayout = findViewById(R.id.colorfulLayout);
}
private void colorChanger() {
final Timer timer = new Timer();
timer.scheduleAtFixedRate(timerTask, 0, 1000);
}
}