Android:用定时器刷 timer 新界面

Android:用定时器刷 timer 新界面

 

在 Android 平台上,界面元素不能在定时器的响应函数里刷新。

以下这段代码中,mButton 的文本并不变化。

public class AndroidTimerDemo extends Activity {
    private Button mButton;
    private Timer mTimer;
    private TimerTask mTimerTask;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mButton = (Button) findViewById(R.id.Button01);

        mTimer = new Timer();

        mTimerTask = new TimerTask() {

            @Override
            public void run() {
                Log.d("AndroidTimerDemo", "timer");
                Calendar cal = Calendar.getInstance();
                mButton.setText(cal.toString());
            }
        };

        mTimer.schedule(mTimerTask, 1000, 1000);
    }
}

在 Android 平台上,UI 单元必须在 Activity 的 context 里刷新。 为了达到想要的效果,可以使用 Message Handler。在定时器响应函数里发送条消息,在 Activity 里响应消息并更新文本。

public class AndroidTimerDemo extends Activity {
    protected static final int UPDATE_TEXT = 0;
    private Button mButton;
    private Timer mTimer;
    private TimerTask mTimerTask;
    private Handler mHandler;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mButton = (Button) findViewById(R.id.Button01);

        mTimer = new Timer();

        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                case UPDATE_TEXT:
                    Calendar cal = Calendar.getInstance();
                    mButton.setText(cal.toString());
                    break;
                }
            }
        };

        mTimerTask = new TimerTask() {

            @Override
            public void run() {
                Log.d("AndroidTimerDemo", "timer");
                mHandler.sendEmptyMessage(UPDATE_TEXT);
/*              
                // It doesn't work updating the UI inside a timer.
                Calendar cal = Calendar.getInstance();
                mButton.setText(cal.toString());
*/          
                }
        };

        mTimer.schedule(mTimerTask, 1000, 1000);
    }
}
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭