【问题标题】:Get height of view programmatically when it is set to Wrap_content设置为 Wrap_content 时以编程方式获取视图高度
【发布时间】:2018-03-31 00:51:40
【问题描述】:

我有一个布局,它的高度设置为 wrap_content。现在我需要在运行时动态获得真正的高度。

我该怎么做?

我试过了:

layout.getLayoutParams().height

但这会给我“-2”,即 Wrap_Content。

谁能帮帮我?

【问题讨论】:

标签: android android-layout


【解决方案1】:

给个赞

viewObj.getHeight():

不是这个

layout.getLayoutParams().height

会有用的

【讨论】:

    【解决方案2】:

    您正在尝试获取尚未绘制的布局高度。

    使用下面的代码sn-p获取布局的高度

    layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    height = layout.getHeight(); // here get the height of the view
                }
            });
    

    【讨论】:

      【解决方案3】:

      当您进入代码下方使用的视图或布局高度和宽度值时..

       textView = findViewById(R.id.textCurve); // first object define it not null then getting value.
      
              Log.d("Height Value:::",""+textView.getHeight());// view control or layout object.
      

      wrap_content 并匹配给定 0 的父值。

      【讨论】:

        猜你喜欢
        • 2011-06-10
        • 1970-01-01
        • 2019-02-03
        • 2019-07-10
        • 2013-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多