Passing resource id from Activity to initialize custom ViewGroup

好久不见. 提交于 2019-12-24 13:33:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!