bar.setProgress(0)不起作用

时间:2014-12-03 05:20:48

标签: android

以下代码来自Beginning Android 3,第20章。当手机旋转时,将创建一个新活动并调用onStart(),因此调用bar.setProgress(0)。但是,我没有看到酒吧的进展又回到了开始阶段。为什么不呢?

public class HandlerDemo extends Activity {
    ProgressBar bar;
    Handler handler=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            bar.incrementProgressBy(5);
        }
    };

    AtomicBoolean isRunning=new AtomicBoolean(false);

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        bar=(ProgressBar)findViewById(R.id.progress);
    }
    public void onStart() {
        super.onStart();
        bar.setProgress(0);
        Thread background=new Thread(new Runnable() {
            public void run() {
                try {
                    for (int i=0;i<20 && isRunning.get();i++) {
                        Thread.sleep(1000);
                        handler.sendMessage(handler.obtainMessage());
                    }
                } catch (Throwable t) {
                // just end the background thread
                }
            }
        });
        isRunning.set(true);
        background.start();
    }

    public void onStop() {
        super.onStop();
        isRunning.set(false);
    }
}

1 个答案:

答案 0 :(得分:1)

尝试使用此代码

@Override
   protected void onPause() {
           super.onPause();
           isRunning.set(false);
           bar.setProgress(0);
   }