androidviewhandlerandroid-custom-viewpostdelayed

Which approach is better for custom View: creating new Handler or using existing one?


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?


Solution

  • 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.