0

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?

soapie
  • 3
  • 4

1 Answers1

0

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
}
DaFa
  • 61
  • 5
  • I am quite new to Android development - would you be able to explain why `View.post (Runnable r)` has its downsides? – soapie Jun 24 '19 at 23:40
  • I cannot give you a reason why, but some people seem to have problem with it here. See [this excellent answer](https://stackoverflow.com/a/24035591/7396293) for more options you could use. – DaFa Jun 24 '19 at 23:45