When I create a new Android app project with Android Studio, the file activity_main.xml contains the following. Why does the TextView have layout_width and layout_height attributes with values wrap_content? I thought that if the view is being laid out with constraints, the layout_width and layout_height are supposed to have values 0dp.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
Answer
      • 2
    • if you have constraints attached with your view then 0dp means 2 things. Either it's match_constraint which is equal to match_parent or it's really 0 dp. In either case you don't need 0dp for a textview do you ?
      • 2
    • Because you can set it? ideally you'd just do match constraints on the view in the layout and set constraint margin from the edge of the parent

Values of the attributes layout_width and layout_height totally depends on your requirement For more information check this link:-

For more information:- https://developer.android.com/reference/android/support/constraint/ConstraintLayout

  • 1
Reply Report
      • 2
    • But if android:layout_width="wrap_content" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" are all set, isn't it over constrained? Not all three will be true when the text is laid out for display.
    • Ahh! The constraints don't actually pull the edge of the text view to the edge of the constraint layout. The constraints happen "outside" the text view. Thanks!

It's not true, depending on you situation you could use either wrap_content or 0dp

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

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

  • Using WRAP_CONTENT, which will ask the widget to compute its own size

  • Using 0dp, which is the equivalent of "MATCH_CONSTRAINT"

And also

When a dimension is set to MATCH_CONSTRAINT, the default behavior is to have the resulting size take all the available space.

More details here ConstraintLayout

  • 0
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions