How can I find the actual width of a view if the XML width attribute is declared as "0dp"?

I have an EditText that has a start and end constraint in a Constraint Layout, along with a width that is declared with a "0dp" in the XML. I am trying to figure out how to obtain the width of the EditText once the application launches, because the 0dp allows the EditText to stretch across the screen while adhering to the start/end constraints.

I've tried calling editText.measuredWidth and editText.layoutParams.width but they both result in a width of 0.

<EditText
            android:id="@+id/editText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginEnd="20dp"
            android:layout_marginStart="10dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toEndOf="@+id/textBox"
            app:layout_constraintEnd_toEndOf="parent"
            android:dropDownWidth="match_parent"
            android:background="@android:color/black"/>

I suspect this result is due to the fact that I am calling it in onCreate in my MainActivity - if that's the case, where should I be trying to call for the width?

1 answer

  • answered 2019-06-24 23:39 DaFa

    An easy way, but one that certainly has its downsides, would be the use of View.post (Runnable r)

    This executes the specified runnable after the view is inflated, when the size of the view is already determined. Calling view.getWidth() should then return the correct result.

    There are other ways of course, but I think of this one as an easy one. Especially with kotlin (and extensions) you could just do

    view.post {
        //do sth with view.getWidth() here
    }