如何将布局 width/height 的值传递给自定义视图 class

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

我正在创建一个具有 class(圆形按钮)扩展线性布局的模块。它包含一个图像视图和一个文本视图。

当在 XML 文件中声明圆形按钮视图时,会分配 layout_width 和 layout_height 值。我希望图像视图尺寸与分配的布局尺寸成比例。因此如何将布局尺寸传递给视图 class 以便我可以将比例尺寸分配给图像视图?

P.S.: 这个问题不涉及传递自定义属性。但处理将 android:layout_widthandroid:layout_height 传递给自定义 UI Class。

我通过将视图实例传递给需要这些值的方法解决了这个问题。然后使用 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
        }
    });
}

即使 class 扩展了一种视图,您也不能执行 this.getViewTreeObserver().addOnGlobalLayoutListener()