-1

I know this question has been asked a lot. But he answers does not work for me.

Here is a simple 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_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" />

In my main activity, I get it that way : final TextView cardNumber = (TextView) findViewById( R.id.cardNumber );

And the I try to measure.

int ww = cardText.getMeasuredWidth();
int hh = cardText.getMeasuredHeight();
Log.v("ww", String.valueOf(ww) ); // => 630
Log.v("hh", String.valueOf(hh) ); // => 127

=> WTF

I can also try to make some constraints on the measurements :

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

This one makes a little bit more sense for the with. But what about the height.

I tried at lot of weird combinaison but I cannot manage to get the height of my text view.

The measure is made on a button click ; so there is no creation state issue.

(the end goal is to auto fit my text ; I found some libraries, but they autofit only in with)

fabien
  • 2,228
  • 2
  • 19
  • 44
  • At time in the lifecycle of the activity are you measuring the width and height? – Barns Oct 27 '17 at 23:56
  • What's the question, exactly? Are you asking why the `dp` (density-independent pixels) values in the layout are different than the pixels values in code? https://stackoverflow.com/q/2025282. – Mike M. Oct 28 '17 at 00:00
  • @ barns : I have a button, I click it to get the measures done => so after every possible life cycle issue – fabien Oct 28 '17 at 00:10
  • OK, I just wanted to be certain that you were not measuring in the `onCreate` method, because the activity is being created and the children views not laid out at that point. But You are obviously already aware of that. – Barns Oct 28 '17 at 00:16

1 Answers1

1

You are getting the value in pixels, but you're setting it in density pixels. If you convert the value returned to DP you will get a very close number. In my case I got 232.38095 as a return.

SRoseDev88
  • 184
  • 6