问题
This is a followup of my previous question where @pskink adviced me to implement custom ViewGroup that will paint what I need. I succeeded with a prototype using hard coded values. I want to move it to further level where I can pass initialization parameters from an Activity. I need to pass a resource id and open an image to be used in onPaint method.
This is the activity. I can get the ViewGroup instance there but it is already instantiated so it makes no sense to pass the resource id in its constructor. I tried to use a setter but I need a Context to initialize Drawable from the resource.
protected void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_puzzle);
hiddenPicture = (TileGroupLayout) findViewById(R.id.hidddenPictureArea);
hiddenPicture.setPictureResource(R.drawable.pic_cute_girl);
ViewGroup's setter does not have the context like the constructor.
public void setPictureResource(int resourceId) {
int pictureResource = resourceId;
mCustomImage = context.getResources().getDrawable(R.drawable.pic_cute_girl);
pictureRect = mCustomImage.getBounds();
}
How to get from this issue? I need to pass the initialization parameter before ViewGroup is painted. Activity has many onXY() methods to override but there is no similar ViewGroup methods. What is its lifecycle?
回答1:
inside your ViewGroup
class, just call getContext()
from anywhere inside of the class.
Edit
on top of getting the context from the ViewGroup
class you actually don't need to call getContext().getResources()
instead you should call getResources()
directly.
来源:https://stackoverflow.com/questions/33460078/passing-resource-id-from-activity-to-initialize-custom-viewgroup