Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You are trying to get width and height of an elements, that weren't drawn yet.</p> <p>If you use debug and stop at some point, you'll see, that your device screen is still empty, that's because your elements weren't drawn yet, so you can't get width and height of something, that doesn't yet exist.</p> <p>And, I might be wrong, but <code>setWidth()</code> is not always respected, <code>Layout</code> lays out it's children and decides how to measure them (calling <code>child.measure()</code>), so If you set <code>setWidth()</code>, you are not guaranteed to get this width after element will be drawn.</p> <p>What you need, is to use <code>getMeasuredWidth()</code> (the most recent measure of your View) somewhere after the view was actually drawn.</p> <p>Look into <code>Activity</code> lifecycle for finding the best moment.</p> <p><a href="http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle" rel="nofollow noreferrer">http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle</a></p> <p>I believe a good practice is to use <code>OnGlobalLayoutListener</code> like this:</p> <pre><code>yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (!mMeasured) { // Here your view is already layed out and measured for the first time mMeasured = true; // Some optional flag to mark, that we already got the sizes } } }); </code></pre> <p>You can place this code directly in <code>onCreate()</code>, and it will be invoked when views will be laid out.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload