androidandroid-layoutdeclare-styleable

How to pass the value of layout width/height to custom view class


I am creating a module having a class (roundbutton) extending linear layout. It contains an image view and a textview.

When the roundbutton view is declared in the XML file, a layout_width and layout_height values are assigned. I want the imageview dimensions to be proportional to the layout dimensions assigned. Hence how to pass the layout dimensions to the view class so that I can assign the proportional dimensions to the image view?

P.S.: This question does not deal with passing custom attributes. But deals with passing the android:layout_width and android:layout_height to the custom UI Class.


Solution

  • I solved this by passing the instance of the view to the method that requires the values. And then use getViewTreeObserver().OnGlobalLayoutListener().

    public void setIcon(final RoundedButton rb, final int drawableResourceId, final int position){
        mIconPosition = position;
    
        rb.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                buttonWidth = rb.getWidth();
                buttonHeight = rb.getHeight();
    
                //whatever needs to be done with the dimensions
            }
        });
    }
    

    You cannot do this.getViewTreeObserver().addOnGlobalLayoutListener() even if the class extends a type of view.