Issue
By default, onDraw() isn't called for ViewGroup.
So I have a question: What happen when we set background drawable for the ViewGroup
Solution
onDraw() is inherited from View class since ViewGroup is subclass of View. So when you set Background on a ViewGroup, it works the same way as any other view. When you call setBackground on a view, it sets requestLayout flag to true and invalidates the view.
Also, Official documentation for View class states that:
If you set a background drawable for a View, then the View will draw it before calling back to its onDraw() method.
You can see how it works in the source code of Android's View class
public void setBackgroundDrawable(Drawable d) {
...
{
requestLayout = true;
}
...
computeOpaqueFlags();
if (requestLayout) {
requestLayout();
}
mBackgroundSizeChanged = true;
invalidate(true);
}
If you look at documentation for invalidate(), you will find
public void invalidate () Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future.
setBackgroundColor() and setBackgroundResource() use setBackgroundDrawable() internally so they work the same way.
So to sum it up, onDraw is called at some point in future when you do setBackground().
Answered By - Zohaib Amir
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.