2

デジタル時計が毎分形式で時刻を更新するときに、TextView のテキストを 1 分ごとに更新したいと考えていますhh/mm。アクティビティに 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();

    }
4

1 に答える 1

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 が 1 分の途中でポップし、TextView は次の分が発生するまで更新されない可能性があるためです。

于 2013-07-14T19:19:00.397 に答える