Java 延迟变色
我想在按下按钮时更改文本视图的背景色。它应该这样做:首先是10毫秒的白色,然后只是正常的颜色。是否有某种延迟函数,或者我是否需要使用循环或某种方式为此编写自己的函数?任何提示都非常感谢: 在这一刻,我只是使用Java 延迟变色,java,android,loops,delay,Java,Android,Loops,Delay,我想在按下按钮时更改文本视图的背景色。它应该这样做:首先是10毫秒的白色,然后只是正常的颜色。是否有某种延迟函数,或者我是否需要使用循环或某种方式为此编写自己的函数?任何提示都非常感谢: 在这一刻,我只是使用 button.setBackgroundColor(Color.parseColor("#ffa500")); 最简单的方法是创建一个处理程序并使用postDelayed执行它: 每个视图都有post和postDelayed方法,分别将runnable发布到UI线程或postDelaye
button.setBackgroundColor(Color.parseColor("#ffa500"));
最简单的方法是创建一个处理程序并使用postDelayed执行它: 每个视图都有post和postDelayed方法,分别将runnable发布到UI线程或postDelayed
button.postDelayed(new Runnable() {
@Override
public void run() {
// change color in here
}
}, 10);
编辑:
如果你要经常打电话,你可以用这样的方式做得更好:
int currentColor;
private Runnable changeColorRunnable = new Runnable() {
@Override
public void run() {
switch(currentColor){
case Color.RED: currentColor = Color.BLACK; break;
case Color.BLACK: currentColor = Color.RED; break;
}
button.setBackgroundColor(currentColor);
}
};
然后:
button.postDelayed(changeColorRunnable, 10);
这将避免不必要的对象创建和垃圾收集您可以在这里找到一些可能性:这是一种非常糟糕的方法。通过这种方式,您将创建一个新对象供GC清理,该对象将只运行一个将休眠的线程。方法View.postdayedrunnable,long是一种更好的方法,因为runnable是一个更小的对象,可以根据需要多次重复使用,而且不需要线程睡眠。太棒了!就这样!其实很简单:谢谢。我甚至用更好的方式更新了我的答案。这有点不太直截了当,但是,你是说它会经常被调用,所以你可以用这种方式来使用更少的内存。就像info一样,我对android编程是新手,但为什么这会使用更少的内存呢?不管怎么说,它确实调用了run方法?移动平台的内存非常有限,所以当我在编程时,我对保存它的最后一个字节都心存疑虑。也就是说,基本Java和面向对象。每次通过关键字“new”时,它都会在内存中创建一个新对象,如果这个对象不再被使用,它将被垃圾收集,这将需要一些额外的处理。这样,它使用更少的内存,因为它只创建一个runnable,并反复使用相同的runnable。有道理吗?但正如我所说,只有当它被多次调用时,这才有意义。
private class ButtonColorChange extends AsyncTask<String, Void, String>
{
protected void onPreExecute()
{
//do
}
protected String doInBackground(String... params)
{
try
{
Thread.sleep(10000); //waiting here
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result)
{
button.setBackgroundColor(Color.parseColor("#ffa500"));
}
}
ButtonColorChange btc = new ButtonColorChange();
btc.execute();