传递资源ID从活动来初始化定制的ViewGroup初始化、资源、ID、ViewGroup

2023-09-12 05:47:47 作者:Bad guy(烂好人)

这是我的previous 问题进行随访那里@pskink谏我来实现自定义的ViewGroup,将油漆我需要什么。我成功地使用硬codeD值的原型。我想将它移动到进一步的水平,我可以从一个活动传递初始化参数。我需要通过一个资源ID和打开图像中OnPaint方法中使用。

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.

这是该活动。我能得到的ViewGroup实例有,但它已经被实例化,所以它是没有意义的传递资源ID在其构造。我试图用一个二传手,但我需要一个背景下,从资源初始化绘制对象。

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中的setter没有像构造的背景下。

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();
}

如何从这个问题得到什么呢?我需要通过初始化参数之前的ViewGroup是画。活动有许多ONXY()方法来覆盖,但没有类似的ViewGroup方法。什么是它的生命周期?

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?

推荐答案

你的的ViewGroup 类中,只需要调用的getContext()从任何地方内之类的。照片 修改 在得到从的ViewGroup 类上下文的顶部,你其实并不需要调用的getContext()。getResources()相反,你应该叫 getResources()直接

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.