Why Does Drawable Have A Reference To A View?
Solution 1:
I was reading Romain Guy's article too. The website/ blog is now gone, Wayback link.
Drawable's have a private field (mCallback
) which refers to an instance of a class which implements the Drawable.Callback
interface, documented here. View implements this interface, and this callback reference is automatically set by the system when view.setBackground
is called.
publicclassViewextendsObjectimplementsDrawable.Callback, KeyEvent.Callback, AccessibilityEventSource {}
Why set this field? It's usage is an implementation detail of Drawable
, so it's difficult to know what exactly its usage is. "The drawable uses this interface to schedule/ execute animation changes." is all I could get from the docs. I guess the main reason is to call void scheduleDrawable(Drawable, Runnable, TimeToExecuteMeasuredSinceAppLaunch)
doc.
Implement this interface if you want to create an animated drawable that extends Drawable. Upon retrieving a drawable, use Drawable#setCallback(android.graphics.drawable.Drawable.Callback) to supply your implementation of the interface to the drawable; it uses this interface to schedule and execute animation changes.
So to answer your questions specifically
why does a drawable have a reference to a view ? To call the interface (
scheduleDrawable
and other interface methods) to animate itself. And also, "to schedule and execute animation changes."what does the drawable do to the view ? The drawable calls those methods in the interface.
does it have a reference to all of the views that use it? The Drawable has 1 callback (so only 1 view can be used), and it can set it with
setCallback
documented here.do all kinds of drawable have references to views ? If you set the
setCallback
, yes. It doesn't have to be "animated" to have the reference, because this (setCallback
) is automatically done withView.setBackground(Drawable) and ImageView.
according to the Drawable docs.
Finally, I find his post confusing, as he glossed over this detail which was the fundamental cause of the memory leak (the Drawable.Callback
interface and more importantly, the mCallback
field). In the end, the callback in Drawable
is stored as private WeakReference<Callback> mCallback = null;
. It is a weak reference which should not cause the memory leak he says. Maybe this was a change to Android after his blog post.
EDIT: Aha! It was Romain who then changed it in 2010:
Solution 2:
1.why does a drawable have a reference to a view ?
A drawable have a reference to a View due to allow it the intercept the view state , suppose that you have a selector-drawable that when view mode change in example pressed, focus, disable change it background
Post a Comment for "Why Does Drawable Have A Reference To A View?"