Android测量文本视图

Android测量文本视图,android,textview,Android,Textview,我知道这个问题被问了很多。但他的回答对我不起作用 下面是一个简单的文本视图: <TextView android:id="@+id/cardText" android:layout_width="240dp" android:layout_height="wrap_content" android:layout_marginEnd="30dp" android:layout_marginStart="30dp" android:layout_

我知道这个问题被问了很多。但他的回答对我不起作用

下面是一个简单的文本视图:

<TextView
    android:id="@+id/cardText"
    android:layout_width="240dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="30dp"
    android:layout_marginStart="30dp"
    android:layout_marginTop="60dp"
    android:background="@color/transparent"
    android:padding="0dp"
    android:paddingBottom="0dp"
    android:paddingEnd="0dp"
    android:paddingStart="0dp"
    android:paddingTop="0dp"
    android:text="hello world"
    android:textSize="36sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
=>WTF

我还可以尝试对测量值进行一些限制:

cardText.measure(View.MeasureSpec.makeMeasureSpec( 240, View.MeasureSpec.EXACTLY), 0);
int ww = cardText.getMeasuredWidth();
int hh = cardText.getMeasuredHeight();
Log.v("ww", String.valueOf(ww) ); // => 240
Log.v("hh", String.valueOf(hh) ); // => 238
这一条对有问题的人来说更有意义。但是高度呢

我尝试了很多奇怪的组合,但我无法获得文本视图的高度

通过点击按钮进行测量;因此,不存在创建状态问题


(最终目标是自动调整我的文本;我找到了一些库,但它们仅在中自动调整)

您获得的值以像素为单位,但设置的是密度像素。如果您将返回的值转换为DP,您将得到一个非常接近的数字。在我的例子中,我得到了232.38095作为回报。

在活动的生命周期中,您是否测量宽度和高度?确切地说,问题是什么?您是否在问为什么布局中的
dp
(与密度无关的像素)值与代码中的像素值不同?@巴恩斯:我有一个按钮,我点击它来完成度量=>所以在每个可能的生命周期发布OK之后,我只是想确定您没有在
onCreate
方法中进行度量,因为此时正在创建活动,并且没有布置子视图。但你显然已经意识到了这一点,我认为你是对的。我需要一些进一步的测试;但这可能是问题所在!
cardText.measure(View.MeasureSpec.makeMeasureSpec( 240, View.MeasureSpec.EXACTLY), 0);
int ww = cardText.getMeasuredWidth();
int hh = cardText.getMeasuredHeight();
Log.v("ww", String.valueOf(ww) ); // => 240
Log.v("hh", String.valueOf(hh) ); // => 238