0

Lately, I was writing a custom View in my Android app, by extending the View class. I needed some looping animation inside and I used new Handler().postDelayed(...) to set a delay between loops. One of my colleagues told me that I don't need to create a new instance of Handler since View already has it, I just needed to call postDelayed(...). This approach seems legit, however, I got suspicious, whether this is a good practice, perhaps it may break something?

I'd like to hear the difference between these approaches, why View has integrated this method postDelayed() and IS IT REALLY THE SAME THING to use this method instead of creating new Handler instance and calling postDelayed() on it?

Kartik Shandilya
  • 3,796
  • 5
  • 24
  • 42
Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52
  • Have you checked this - https://stackoverflow.com/questions/41728973/what-is-the-difference-between-view-postdelayed-and-handler-postdelayed-on-t – Kartik Shandilya Jul 04 '19 at 12:17
  • @NovoLucas Yes, of course, however it doesn't answer my question, I don't ask for difference, more for the better approach here. Also, that question has only 1 answer, which I found insufficient. – Sergey Emeliyanov Jul 04 '19 at 12:20

1 Answers1

3

The handler is provided by AttachInfo Object. It is a final class in the View. Contains a lot of information about the view.

    /**
     * A Handler supplied by a view's {@link android.view.ViewRootImpl}. This
     * handler can be used to pump events in the UI events queue.
     */
    final Handler mHandler;

You can check the View class Documentation

And yes, you can use it rather than creating your own.

Lakhwinder Singh
  • 6,799
  • 4
  • 25
  • 42