如何在Android中的数字时钟期间刷新TextView?

时间:2012-11-12 15:13:46

标签: android textview clock digital

当数字时钟每分钟以hh/mm格式刷新时,我想每分钟刷新一次TextView的文本。我在Activity中放了一个名为txtView1的TextView并创建了一个类Digital Clock。当我运行应用程序时,然而,该应用程序退出时出现错误。我真的不知道为什么 这是关于数字时钟的重要功能onAttachedToWindow()

 protected void onAttachedToWindow() {
       mTickerStopped = false;

        super.onAttachedToWindow();

        mHandler = new Handler();


        /**

         * requests a tick on the next hard-second boundary

         */

        mTicker = new Runnable() {

                public void run() {

                    if (mTickerStopped) return;

                    mCalendar.setTimeInMillis(System.currentTimeMillis());

                    String content = (String) DateFormat.format(mFormat, mCalendar);

                    if(content.split(" ").length > 1){



                        content = content.split(" ")[0] + content.split(" ")[1];

                    }

                    setText(android.text.Html.fromHtml(content));

                   //-----Here is the TextView I want to refresh

                   TextView txtV1 = (TextView)findViewById(R.id.txtView1);
                   txtV1.setText("Now Fresh");//Just for try,so set a constant string 

                    invalidate();

                    long now = SystemClock.uptimeMillis();

                    //refresh each minute

                    long next = now + (60*1000 - now % 1000);

                    mHandler.postAtTime(mTicker, next);

                }

            };

        mTicker.run();

    }

1 个答案:

答案 0 :(得分:0)

系统根据系统时钟在每分钟的确切开始发送广播事件。最可靠的方法是这样做:

BroadcastReceiver _broadcastReceiver;
private final SimpleDateFormat _sdfWatchTime = new SimpleDateFormat("HH:mm");
private TextView _tvTime;

@Override
public void onStart() {
    super.onStart();
    _broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context ctx, Intent intent) {
                if (intent.getAction().compareTo(Intent.ACTION_TIME_TICK) == 0)
                    _tvTime.setText(_sdfWatchTime.format(new Date()));
            }
        };

    registerReceiver(_broadcastReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}

@Override
public void onStop() {
    super.onStop();
    if (_broadcastReceiver != null)
        unregisterReceiver(_broadcastReceiver);
}

不要忘记事先初始化TextView(到当前系统时间),因为很可能你会在一分钟内弹出你的UI,而TextView在下一分钟发生之前不会更新。