我想每秒更改coordinatorLayout
的背景颜色
但是,我发现,颜色coordinatorLayout
从初始颜色RED
变为直接最后一种颜色,即#09FF00
数组中的COLORS
。尽管中间颜色已记录在LogCat
中,但中间颜色不会显示在布局中
我做错了什么?
public class ColorActivity extends AppCompatActivity {
private static String COLORS [] = {"#FF0000", "#0000FF", "#09FF00"};
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detect);
final CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.fullscreenview);
coordinatorLayout.setBackgroundColor(Color.RED);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
}catch (Exception e) {
e.printStackTrace();
}
changeColor(coordinatorLayout);
}
}).start();
}
private void changeColor(final CoordinatorLayout coordinatorLayout) {
runOnUiThread(new Runnable() {
@Override
public void run() {
for (String color: COLORS) {
Log.i("COLOR", color);
coordinatorLayout.setBackgroundColor(Color.parseColor(color));
}
}
});
}
}
答案 0 :(得分:0)
实际上代码中存在逻辑上的问题
for (String color: COLORS) {
Log.i("COLOR", color);
coordinatorLayout.setBackgroundColor(Color.parseColor(color));
}
循环执行得如此之快,你将无法实现中间色。我建议改变
new Thread(new Runnable() {
@Override
public void run() {
int colorIndex = 0;
do{
try {
changeColor(coordinatorLayout,COLORS[colorIndex++]);
Thread.sleep(100);
}catch (Exception e) {
e.printStackTrace();
}
}while(iteration < COLORS.length)
}
}).start();
private void changeColor(final CoordinatorLayout coordinatorLayout,final String color) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("COLOR", color);
coordinatorLayout.setBackgroundColor(Color.parseColor(color));
}
});
}
答案 1 :(得分:0)
如果您的计时器逻辑每秒触发一次,那么在调用changeColor之前从COLORS获得单色,然后使用它。
喜欢这个......
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
}catch (Exception e) {
e.printStackTrace();
}
//get single color here
//update color and pass it
changeColor(coordinatorLayout, color);
}
}).start();
private void changeColor(final CoordinatorLayout coordinatorLayout, color mcolor) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("COLOR", mcolor);
coordinatorLayout.setBackgroundColor(Color.parseColor(mcolor));
}
});
}