Where do I set the size of the view, which is a class field spreading the RelativeLayout?

I have a class MyLayout

extending RelativeLayout

that includes a type field View

. MyLayout

the object is created in the xml layout file, so all properties are set there. I need to programmatically set the size of a field View

, which depends on the size of its parent ( MyLayout

).

I tried to set it in the constructor, but when I try to use the method getWidth()

it returns 0, so I assume the size hasn't been set yet inside the constructor. I also tried to set it in the method onDraw()

, but when I run the app, this inner one View

shows up as the second one with its default size, and after that it scales to the size I want . Then I tried putting it inside a method onMeasure()

, but this call is called multiple times, so again it doesn't seem to be efficient.

So what might be the best place to install it?

This is my class:

public class MyLayout extends RelativeLayout {

    private View pointer;

    public MyLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        init(context);
    }

    public MyLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        init(context);
    }

    public MyLayout(Context context) {
        super(context);

        init(context);
    }

    private void init(Context c) {
        pointer = new View(c);
        pointer.setBackgroundResource(R.drawable.pointer);
        addView(pointer);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)pointer.getLayoutParams();
        lp.height = (int)(getHeight() * 0.198);
        lp.width = (int)(getWidth() * 0.198);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

      

+3


source to share


1 answer


in your MyLayout class, override onSizeChanged ():



protected void onSizeChanged(int w, int h, int oldw, int oldh) {

     RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)pointer.getLayoutParams();
     lp.height = (int)(getHeight() * 0.198);
     lp.width = (int)(getWidth() * 0.198);

};

      

+1


source







All Articles