Satori_Kanzo
@Satori_Kanzo
Make code not war

Проблемка с Handler();, как решить без имплементации стандартных методов?

Пример из книжки Head First Android Development (2015) (не перевод, упаси меня XOR). Суть в том, что Handler используется для того, чтобы метод происходил в главном потоке, либо не мешал ему (пока не понял до конца), сам метод, описаный ниже, вызывается в onCreate();. Компилятор ругается на то, что Handler, дескать, абстрактный, поэтому нужно его внутренности, собственно, реализовать, но судя по продолжению в книге "Как мы видим, на эмуляторе приложение работает просто отлично", куда уж лучше, если не считать Сompilation failed =_=

Непосредственно метод (все с комментариями, думаю можно понять чего я от него хочу):

private void runTimer() {
        final TextView timeView = (TextView)findViewById(R.id.time_view); // get the text view
        final Handler handler = new Handler(); // create a new Handler
        handler.post(new Runnable() { //call the post() method, passing in a new Runnable. The post() method
                                     //process codes without a delay, so the code in Runnable will
                                     //run almost immediately
            @Override
            public void run() {     //the Runnable run() method contains the code you want to be run. In
                //our case the code to update the text view.
                int hours = seconds / 3600;                                           //format the seconds into
                int minutes = (seconds % 3600) / 60;                                    //hours, minutes, and seconds.
                int secs = seconds % 60;                                              //Just plain Java code.
                String time = String.format("%d:%02d:%02d", hours, minutes, secs);  //

                timeView.setText(time); // set the text view text

                if (running) {   // if running is true, increment
                    seconds++;  // the seconds variable
                }
                handler.postDelayed(this, 1000); //Post the code in the Runnable to be run again after a delay
                                                //of 1000 milliseconds, or 1 second. At this line of code it
                                                 //included in the runnable run() method, this will keep getting called.
            }
        });
    }
  • Вопрос задан
  • 160 просмотров
Решения вопроса 1
Ewintory
@Ewintory
Java / Android developer
Скорее всего ты импортировал не тот Handler. Их там много, проверь импорты.
Сто процентов взял из пакета логгирования, а нужно из android.os
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы