为什么我的循环变慢?

时间:2018-03-09 09:23:10

标签: java android handler

我有一个“财富之轮”,有3个基于图像的字段。我试图将图像视图的资源更改为轮子正在旋转,但显然Handler Delay作为延迟循环,在我的手机上运行得太慢了。 (三星S8)。

ImageView wheel;
int round = 0;
int millis = 10;

private final Handler mHandler = new Handler();

private final Runnable mUpdateUI = new Runnable() {
    public void run() {

        wheel = (ImageView) findViewById(R.id.feld_wheel);

        if (round == 0) {
            wheel.setImageResource(R.drawable.wheel_1);
        } else if (round == 1) {
            wheel.setImageResource(R.drawable.wheel_2);
        } else {
            wheel.setImageResource(R.drawable.wheel_3);
        }

        round += 1;
        if (round > 3) {
            round = 0;
        }
        //Decelerator
        millis += 10;

        mHandler.postDelayed(mUpdateUI, millis);
    }
};

执行按钮

public void onClick() {
    mHandler.post(mUpdateUI);
}

2 个答案:

答案 0 :(得分:0)

您将延迟递增到处理程序的每次执行中,使用以下行: millis + = 10; 通过这样做,你不会加速,但做的恰恰相反。 您正在递增处理程序在下一次执行mUpdateUI之前等待的延迟

  

OP故意使处理程序减速,因此这部分问题并不相关

然后,确保您进入主线程,否则您将无法获得UI更新。如果您不是,请尝试使用runOnUiThread

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        ...
    }
});

答案 1 :(得分:0)

缓存drawable,而不是一直重新分配它们。应该以内存为代价加速循环。也摆脱了永久的findViewById

ImageView wheel;
int round = 0;
int millis = 10;
Drawable wheel1;
Drawable wheel2;
Drawable wheel3;

//initialite drawables
onCreate(){
...
    wheel1 = getResources().getDrawable(R.drawable.wheel_1)
    wheel2 = getResources().getDrawable(R.drawable.wheel_2)
    wheel3 = getResources().getDrawable(R.drawable.wheel_3)
    wheel = (ImageView) findViewById(R.id.feld_wheel);
...
}


private final Handler mHandler = new Handler();

private final Runnable mUpdateUI = new Runnable() {
    public void run(){

        if (round == 0) {
            wheel.setImageDrawable(wheel1);
        } else if (round == 1) {
            wheel.setImageDrawable(wheel2);
        } else {
            wheel.setImageDrawable(wheel3);
        }

        round += 1;
        if (round > 3) {
            round = 0;
        }
        //Decelerator
        millis += 10;

        mHandler.postDelayed(mUpdateUI, millis);
    }
};