处理程序与ProgressBar

时间:2013-08-19 15:04:42

标签: java android progress-bar handler

当我触摸超过5个Seonds的显示器时,我正在尝试创建延迟动作。 我正在使用Handler和Runnable,使用handler.postDelayed(runnable, 5000); 我还想要一个ProgressBar来展示Handler何时启动。从我发现的研究中,我必须覆盖handleMessage()方法..这就是我尝试过的。

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        progress.setProgress(progress.getProgress() + 100);
        sendEmptyMessageDelayed(0, 100);
    }
};
private Runnable runnable = new Runnable() {
    public void run() {
        playAlarm();
    }
};

...

progress = (ProgressBar) findViewById(R.id.progressBar1);

...

@Override
public boolean onTouchEvent(MotionEvent e) {
    if (e.getAction() == MotionEvent.ACTION_DOWN) {
        // Execute Runnable after 5000 milliseconds = 5 seconds.
        progress.setProgress(0);
        handler.postDelayed(runnable, 5000);
        mBooleanIsPressed = true;
    }

    if (e.getAction() == MotionEvent.ACTION_UP) {
        if (mBooleanIsPressed) {
            mBooleanIsPressed = false;
            progress.setProgress(0);
            handler.removeCallbacks(runnable);
        }
    }
    return true;
}

它没有崩溃。但ProgressBar根本没有显示任何内容。

1 个答案:

答案 0 :(得分:0)

如果你想使用一个处理程序,那么一些东西会丢失,这应该可行(未经测试):

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
    super.handleMessage(msg);
    progress.setProgress(progress.getProgress() + 100);
    if (mBooleanIsPressed)
        sendEmptyMessageDelayed(0, 100);
}
};
private Runnable runnable = new Runnable() {
public void run() {
    playAlarm();
}
};

...

progress = (ProgressBar) findViewById(R.id.progressBar1);

...

@Override
public boolean onTouchEvent(MotionEvent e) {
// only start your handler if the view isn't touched
if (e.getAction() == MotionEvent.ACTION_DOWN && !mBooleanIsPressed) {
    // Execute Runnable after 5000 milliseconds = 5 seconds.
    progress.setProgress(0);
    handler.postDelayed(runnable, 5000);
    // send the first empty message, which will be handled...
    sendEmptyMessageDelayed(0, 100);
    mBooleanIsPressed = true;
}

if (e.getAction() == MotionEvent.ACTION_UP) {
    if (mBooleanIsPressed) {
        mBooleanIsPressed = false;
        progress.setProgress(0);
        handler.removeCallbacks(runnable);
    }
}
return true;
}

随时问你是否有任何问题