W3hri
W3hri

Reputation: 1591

Width of FrameLayout never truly 0

I'm currently facing a strange bug(?) with ConstraintLayout. Im trying to set the width of a FrameLayout, which is a child of a Constraintlayout, to 0px.

I set the width via the following code snippet:

// set width
val newWidth = 0
val frameParams = frame.layoutParams as ConstraintLayout.LayoutParams
frameParams.width = newWidth
frame.layoutParams = frameParams
logE("newWidth: $newWidth, frame.measuredWidth: ${frame.measuredWidth}, frame.width: ${frame.width}")

Strangely, it seems that my FrameLayout never reaches a "true" width of 0px, but some random values close to 0. See a selection of logs below:

E/Log: newWidth: 0, frame.measuredWidth: 6, frame.width: 6
E/Log: newWidth: 0, frame.measuredWidth: 10, frame.width: 10
E/Log: newWidth: 0, frame.measuredWidth: 1, frame.width: 1

As you can see, neither the FrameLayouts width, nor its measuredWidth, reach a value of 0. Is this a known bug, and if so, does anyone know a workaround?

Please let me know if you need any further information. Thanks in advance!

Upvotes: 1

Views: 200

Answers (1)

Mauker
Mauker

Reputation: 11497

That’s not a bug at all. In constraint layout the 0dp is evaluated as match_constraint, which will take up space based on the constraints you defined.

As stated on the docs:

The dimension of the widgets can be specified by setting the android:layout_width and android:layout_height attributes in 3 different ways:

1- Using a specific dimension (either a literal value such as 123dp or a Dimension reference);

2- Using WRAP_CONTENT, which will ask the widget to compute its own size;

3- Using 0dp, which is the equivalent of MATCH_CONSTRAINT.

If your goal is to make a view disappear, you can change its visibility instead of changing the width or height.

val view: View = findViewById(R.id.yourView)
view.visibility = View.GONE // Or View.INVISIBLE

Now if you're looking to change the width/height for animation purposes, or for any other reason, change it to 1dp or any other size that fits your needs.

You can read more about ConstraintLayout on the Android training guide and on its docs.

Upvotes: 3

Related Questions