【问题标题】:How to pass the value of layout width/height to custom view class如何将布局宽度/高度的值传递给自定义视图类
【发布时间】:2016-09-06 06:47:21
【问题描述】:

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

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

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

【问题讨论】:

标签: android android-layout declare-styleable


【解决方案1】:

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

即使类扩展了一种视图,你也不能this.getViewTreeObserver().addOnGlobalLayoutListener()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-02
    • 2016-04-18
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 2014-08-10
    相关资源
    最近更新 更多