我有一个 View
,我想在一定时间内更改 View 的BackgroundColor
。假设我想在 20 分钟内每秒将 View
的颜色更改为红色和绿色。
我已经尝试过的:
final static int INTERVAL = 10000; // 1 second
private static View myView = null;
boolean whichColor = true;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = (View) findViewById(R.id.my_view);
myView.setBackgroundColor(Color.RED);// set initial colour
new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(INTERVAL);
}
catch (InterruptedException e) {
e.printStackTrace();
}
updateColor();
whichColor = !whichColor;
}
}
}).start();
}
private void updateColor() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (whichColor)
myView.setBackgroundColor(Color.RED);
else
myView.setBackgroundColor(Color.GREEN);
}
});
}
}
这是每秒改变 View 的颜色,但我只想在一个时间限制内改变。有什么办法可以做到这一点? 任何帮助将不胜感激。
最佳答案
你必须保持对 Runnable
中的计数器的引用:
new Thread(new Runnable() {
private static final int MAX_COUNT = 20 * 60;
int counter = 0;
public void run() {
while (counter < MAX_COUNT) {
try {
Thread.sleep(INTERVAL);
}
catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
updateColor();
whichColor = !whichColor;
}
}
}).start();
备选方案:
使用Handler
类及其消息系统。
创建扩展 Handler
的类:
public class BlinkingHandler extends Handler {
private static final int MAX_COUNT = 20 * 60;
int counter = 0;
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 123) {
counter++;
//Change background color
if (counter < MAX_COUNT) {
this.sendEmptyMessageDelayed(123, DateUtils.SECOND_IN_MILLIS);
}
}
}
}
初始化您的处理程序
:
BlinkingHandler handler = new BlinkingHandler();
handler.sendEmptyMessage(123);
关于android - 在时间限制内每秒更改一次 View 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39661865/