Missing constraints in constraint layout как исправить

Learn how to resolve missing constraint errors and harcoded text warnings in Android Studio.

As you set out on your exciting journey as an Android developer, you will almost certainly encounter errors in your applications. For example, you may notice the Android Studio editor sometimes has a red or yellow warning sign in the top right corner. These warning signs indicate there is a problem with the application’s code. Red warnings indicate a critical error that will prevent the app from running, while yellow warnings are advisory.

redwarning.png

To find out more information, click the warning sign and Android Studio should explain the reason for the error. In this tutorial, we will explore how to resolve two common errors, which are called «Missing Constraints in ConstraintLayout» and «Hardcoded text», respectively.

Constraint errors

Constraints are a set of rules which determine how an object positions itself relative to other objects and the wider layout. Without constraints, the objects in your app would likely jump out of position when the app is loaded or the device is rotated. To automatically apply any missing constraints you can press the ‘Infer Constraints’ button at the top of the editor.

infer.png

The red warning sign should now have turned yellow because we have resolved the missing constraints error. Also, the TextView object should have blue arrows coming out of it when selected in the editor. These blue arrows represent the constraints. They determine how the TextView object will position itself relative to the edges of the app interface.

constraints.png

The infer constraints button adds any missing constraints and resolves the error, but what if you want to fine-tune the position of the object? To adjust the position of an object, select it and refer to the Attributes panel. In this example, inferring constraints created a top margin of 99dp.

margin.png

A margin is a type of constraint that creates a fixed distance between the object and another reference point (e.g. another object or the edge of the app interface). In the above example, we can adjust the distance between the TextView object and the top of the app layout by editing the value of the layout_marginTop attribute. For instance, if you wanted the TextView to sit near the top of the screen then you could set the layout_marginTop attribute to a small value such as 20dp.

An alternative method for adding constraints is to drag and drop the blue arrows yourself. To illustrate how this is done, add a second TextView object below the first one (for a reminder on how to add TextView objects see this tutorial). Next, select the original TextView object and notice the four circles which appear on each side. Click the bottom circle and drag the arrow down to the top circle of the second TextView object. This creates a constraint connecting the two TextView objects. Note the second TextView object will now have some missing constraints of its own. You can fix this using the Infer Constraints button or by dragging the constraint arrows to the edge of the app layout yourself.

connectingconstraints.png

Hardcoded text warnings

While the TextView widgets now have the appropriate constraints, there is still a yellow warning sign in the top right corner of the editor.

yellowwarning.png

This yellow warning sign is there because the TextView widgets contain hardcoded text. Hardcoded text is text that is written directly into the layout file’s code. It can cause issues when the underlying code is being read and edited. Fortunately, hardcoded text is quite easy to rectify. Simply click the yellow warning sign in the top right corner, scroll to the bottom of the hardcoded text error message and press the ‘Fix’ button. In the Extract Resource window that opens, you can simply press OK and the attribute with the hardcoded text will be converted to a String resource. Android apps store all user-facing text as Strings in a resource file. The advantage of this is that a single String resource can be used in multiple locations throughout the app. If you ever need to change a String’s text, then you only need to update a single resource rather than tracking down all the areas that use the text. String resources also make it easier to translate your app into different languages.

hardcode.png

For larger projects, it is often best to define any text (or Strings) you intend to use in advance. That way you can prevent the hardcoded text warning from ever appearing. To define a String, open the Strings resource file by clicking Project > app > res > values > Strings.xml

strings-resource-file.png

There will likely already be some Strings in there. Simply add new Strings between the opening <resources> and closing </resources> resources tags in the following format:

<string name="title">Coders' Guidebook</string>

The ‘name’ property is what you will use to refer to the String elsewhere in the app. The text between the two String tags will be displayed to the user whenever the String name is referred to. In other words, using the ‘title’ String will display ‘Coders’ Guidebook’.

<<< Previous

Next >>>

Как исправить ошибку в android studio?

Когда добавляю любой элемент, показывает эту ошибку
5bd84e1cba666062446314.png

Текст, который на скрине

Missing Contraints in ContraintsLayout
This view is not constrained. It only has designtime positions, so it will jump to (0,0) at runtime unless you add the constraints The layout editor allows you to place widgets anywhere on the canvas, and it records the current position with designtime attributes (such as layout_editor_absoluteX). These attributes are not applied at runtime, so if you push your layout on a device, the widgets may appear in a different location than shown in the editor. To fix this, make sure a widget has both horizontal and vertical constraints by dragging from the edge connections.

Build a Responsive UI with ConstraintLayout

ConstraintLayout allows you to create large and complex layouts with a flat view hierarchy (no nested view groups). It’s similar to RelativeLayout in that all views are laid out according to relationships between sibling views and the parent layout, but it’s more flexible than RelativeLayout and easier to use with Android Studio’s Layout Editor.

All the power of ConstraintLayout is available directly from the Layout Editor’s visual tools, because the layout API and the Layout Editor were specially built for each other. So you can build your layout with ConstraintLayout entirely by drag-and-dropping instead of editing the XML.

ConstraintLayout is available in an API library that’s compatible with Android 2.3 (API level 9) and higher. This page provides a guide to building a layout with ConstraintLayout in Android Studio 3.0 or higher. If you’d like more information about the Layout Editor itself, see the Android Studio guide to Build a UI with Layout Editor.

To see a variety of layouts you can create with ConstraintLayout , check out the Constraint Layout Examples project on GitHub.

Constraints overview

To define a view’s position in ConstraintLayout , you must add at least one horizontal and one vertical constraint for the view. Each constraint represents a connection or alignment to another view, the parent layout, or an invisible guideline. Each constraint defines the view’s position along either the vertical or horizontal axis; so each view must have a minimum of one constraint for each axis, but often more are necessary.

When you drop a view into the Layout Editor, it stays where you leave it even if it has no constraints. However, this is only to make editing easier; if a view has no constraints when you run your layout on a device, it is drawn at position [0,0] (the top-left corner).

In figure 1, the layout looks good in the editor, but there’s no vertical constraint on view C. When this layout draws on a device, view C horizontally aligns with the left and right edges of view A, but appears at the top of the screen because it has no vertical constraint.

Figure 1. The editor shows view C below A, but it has no vertical constraint

Figure 2. View C is now vertically constrained below view A

Although a missing constraint won’t cause a compilation error, the Layout Editor indicates missing constraints as an error in the toolbar. To view the errors and other warnings, click Show Warnings and Errors . To help you avoid missing constraints, the Layout Editor can automatically add constraints for you with the Autoconnect and infer constraints features.

Add ConstraintLayout to your project

To use ConstraintLayout in your project, proceed as follows:

  1. Ensure you have the maven.google.com repository declared in your module-level build.gradle file:
  2. Add the library as a dependency in the same build.gradle file:
  3. In the toolbar or sync notification, click Sync Project with Gradle Files.

Now you’re ready to build your layout with ConstraintLayout .

Convert a layout

Figure 3. The menu to convert a layout to ConstraintLayout

To convert an existing layout to a constraint layout, follow these steps:

  1. Open your layout in Android Studio and click the Design tab at the bottom of the editor window.
  2. In the Component Tree window, right-click the layout and click Convert layoutto ConstraintLayout.

Create a new layout

To start a new constraint layout file, follow these steps:

  1. In the Project window, click the module folder and then select File > New > XML > Layout XML.
  2. Enter a name for the layout file and enter “android.support.constraint.ConstraintLayout” for the Root Tag.
  3. Click Finish.

Add a constraint

Start by dragging a view from the Palette window into the editor. When you add a view in a ConstraintLayout , it displays a bounding box with square resizing handles on each corner and circular constraint handles on each side.

Video 1. The left side of a view is constrained to the left side of the parent

Click the view to select it. Then click-and-hold one of the constraint handles and drag the line to an available anchor point (the edge of another view, the edge of the layout, or a guideline). When you release, the constraint is made, with a default margin separating the two views.

When creating constraints, remember the following rules:

  • Every view must have at least two constraints: one horizontal and one vertical.
  • You can create constraints only between a constraint handle and an anchor point that share the same plane. So a vertical plane (the left and right sides) of a view can be constrained only to another vertical plane; and baselines can constrain only to other baselines.
  • Each constraint handle can be used for just one constraint, but you can create multiple constraints (from different views) to the same anchor point.

Video 2. Adding a constraint that opposes an existing one

To remove a constraint, select the view and then click the constraint handle. Or remove all the constraints by selecting the view and then clicking Delete Constraints .

If you add opposing constraints on a view, the constraint lines become squiggly like a spring to indicate the opposing forces, as shown in video 2. The effect is most visible when the view size is set to “fixed” or “wrap content,” in which case the view is centered between the constraints. If you instead want the view to stretch its size to meet the constraints, switch the size to “match constraints”; or if you want to keep the current size but move the view so that it is not centered, adjust the constraint bias.

You can use constraints to achieve different types of layout behavior, as described in the following sections.

Parent position

Constrain the side of a view to the corresponding edge of the layout.

In figure 4, the left side of the view is connected to the left edge of the parent layout. You can define the distance from the edge with margin.

Figure 4. A horizontal constraint to the parent

Order position

Define the order of appearance for two views, either vertically or horizontally.

In figure 5, B is constrained to always be to the right of A, and C is constrained below A. However, these constraints do not imply alignment, so B can still move up and down.

Figure 5. A horizontal and vertical constraint

Alignment

Align the edge of a view to the same edge of another view.

In figure 6, the left side of B is aligned to the left side of A. If you want to align the view centers, create a constraint on both sides.

You can offset the alignment by dragging the view inward from the constraint. For example, figure 7 shows B with a 24dp offset alignment. The offset is defined by the constrained view’s margin.

You can also select all the views you want to align, and then click Align in the toolbar to select the alignment type.

Figure 6. A horizontal alignment constraint

Figure 7. An offset horizontal alignment constraint

Baseline alignment

Align the text baseline of a view to the text baseline of another view.

In figure 8, the first line of B is aligned with the text in A.

To create a baseline constraint, select the text view you want to constrain and then click Edit Baseline , which appears below the view. Then click the text baseline and drag the line to another baseline.

Figure 8. A baseline alignment constraint

Constrain to a guideline

You can add a vertical or horizontal guideline to which you can constrain views, and the guideline will be invisible to app users. You can position the guideline within the layout based on either dp units or percent, relative to the layout’s edge.

To create a guideline, click Guidelines in the toolbar, and then click either Add Vertical Guideline or Add Horizontal Guideline.

Drag the dotted line to reposition it and click the circle at the edge of the guideline to toggle the measurement mode.

Figure 9. A view constrained to a guideline

Constrain to a barrier

Similar to a guideline, a barrier is an invisible line that you can constrain views to. Except a barrier does not define its own position; instead, the barrier position moves based on the position of views contained within it. This is useful when you want to constrain a view to the a set of views rather than to one specific view.

For example, figure 10 shows view C is constrained to the right side of a barrier. The barrier is set to the “end” (or the right side in a left-to-right layout) of both view A and view B. So the barrier moves depending on whether the right side of view A or view B is is farthest right.

To create a barrier, follow these steps:

  1. Click Guidelines in the toolbar, and then click Add Vertical Barrieror Add Horizontal Barrier.
  2. In the Component Tree window, select the views you want inside the barrier and drag them into the barrier component.
  3. Select the barrier from the Component Tree, open the Attributes window, and then set the barrierDirection.

Now you can create a constraint from another view to the barrier.

You can also constrain views that are inside the barrier to the barrier. This way, you can ensure that all views in the barrier always align to each other, even if you don’t know which view will be the longest or tallest.

You can also include a guideline inside a barrier to ensure a “minimum” position for the barrier.

Figure 9. View C is constrained to a barrier, which moves based on the position/size of both view A and view B

Adjust the constraint bias

When you add a constraint to both sides of a view (and the view size for the same dimension is either “fixed” or “wrap content”), the view becomes centered between the two constraints with a bias of 50% by default. You can adjust the bias by dragging the bias slider in the Attributes window or by dragging the view, as shown in video 5.

If you instead want the view to stretch its size to meet the constraints, switch the size to “match constraints”.

Video 5. Adjusting the constraint bias

Adjust the view size

Figure 10. The Attributes window includes controls for 1 size ratio, 2 delete constraint, 3 height/width mode, 4 margins, and 5 constraint bias.

You can use the corner handles to resize a view, but this hard codes the size so the view will not resize for different content or screen sizes. To select a different sizing mode, click a view and open the Attributes window on the right side of the editor.

Near the top of the Attributes window is the view inspector, which includes controls for several layout attributes, as shown in figure 10 (this is available only for views in a constraint layout).

You can change the way the height and width are calculated by clicking the symbols indicated with callout 3 in figure 10. These symbols represent the size mode as follows (click the symbol to toggle between these settings):

  • Fixed: You specify a specific dimension in the text box below or by resizing the view in the editor.
  • Wrap Content: The view expands only as much as needed to fit its contents.
  • Match Constraints: The view expands as much as possible to meet the constraints on each side (after accounting for the view’s margins). However, you can modify that behavior with the following attributes and values (these attributes take effect only when you set the view width to match constraints):
    • layout_constraintWidth_default
      • spread: Expands the view as much as possible to meet the constraints on each side. This is the default behavior.
      • wrap: Expands the view only as much as needed to fit its contents, but still allows the view to be smaller than that if the constraints require it. So the difference between this and using Wrap Content (above), is that setting the width to Wrap Content forces the width to always exactly match the content width; whereas using Match Constraints with layout_constraintWidth_default set to wrap also allows the view to be smaller than the content width.

      Note: You cannot use match_parent for any view in a ConstraintLayout . Instead use “match constraints” ( 0dp ).

      Figure 11. The view is set to a 16:9 aspect with the width based on a ratio of the height.

      Set size as a ratio

      You can set the view size to a ratio such as 16:9 if at least one of the view dimensions is set to “match constraints” ( 0dp ). To enable the ratio, click Toggle Aspect Ratio Constraint (callout 1 in figure 10), and then enter the width : height ratio in the input that appears.

      If both the width and height are set to match constraints, you can click Toggle Aspect Ratio Constraint to select which dimension is based on a ratio of the other. The view inspector indicates which is set as a ratio by connecting the corresponding edges with a solid line.

      For example, if you set both sides to “match constraints”, click Toggle Aspect Ratio Constraint twice to set the width be a ratio of the height. Now the entire size is dictated by the height of the view (which can be defined in any way) as shown in figure 11.

      Adjust the view margins

      To ensure that all your views are evenly spaced, click Margin in the toolbar to select the default margin for each view that you add to the layout. Any change you make to the default margin applies only to the views you add from then on.

      You can control the margin for each view in the Attributes window by clicking the number on the line that represents each constraint (in figure 10, callout 4 shows the bottom margin is set to 28dp).

      Figure 12. The toolbar’s Margin button.

      All margins offered by the tool are factors of 8dp to help your views align to Material Design’s 8dp square grid recommendations.

      Control linear groups with a chain

      A chain is a group of views that are linked to each other with bi-directional position constraints. For example, figure 13 shows two views that both have a constraint to each other, thus creating a horizontal chain.

      A chain allows you to distribute a group of views horizontally or vertically with the following styles (as shown in figure 14):

      1. Spread: The views are evenly distributed (after margins are accounted for). This is the default.
      2. Spread inside: The first and last view are affixed to the constraints on each end of the chain and the rest are evenly distributed.
      3. Weighted: When the chain is set to either spread or spread inside, you can fill the remaining space by setting one or more views to “match constraints” ( 0dp ). By default, the space is evenly distributed between each view that’s set to “match constraints,” but you can assign a weight of importance to each view using the layout_constraintHorizontal_weight and layout_constraintVertical_weight attributes. If you’re familiar with layout_weight in a linear layout, this works the same way. So the view with the highest weight value gets the most amount of space; views that have the same weight get the same amount of space.
      4. Packed: The views are packed together (after margins are accounted for). You can then adjust the whole chain’s bias (left/right or up/down) by changing the chain’s head view bias.

      The chain’s “head” view (the left-most view in a horizontal chain and the top-most view in a vertical chain) defines the chain’s style in XML. However, you can toggle between spread, spread inside, and packed by selecting any view in the chain and then clicking the chain button that appears below the view.

      To create a chain of views quickly, select them all, right-click one of the views, and then select either Center Horizontally or Center Vertically, to create either a horizontal or vertical chain, respectively (see video 4).

      A few other things to consider when using chains:

      • A view can be a part of both a horizontal and a vertical chain, making it easy to build flexible grid layouts.
      • A chain works properly only if each end of the chain is constrained to another object on the same axis, as shown in figure 13.
      • Although the orientation of a chain is either vertical or horizontal, using one does not align the views in that direction. So be sure you include other constraints to achieve the proper position for each view in the chain, such as alignment constraints.

      Figure 13. A chain with just two views

      Figure 14. Examples of each chain style

      Video 4. Creating a chain from the action menu

      Automatically create constraints

      Instead of adding constraints to every view as you place them in the layout, you can move each view into the positions you desire, and then click Infer Constraints to automatically create constraints.

      Infer Constraints scans the layout to determine the most effective set of constraints for all views. It makes a best effort to constrain the views to their current positions while allowing flexibility. You might need to make some adjustments to be sure the layout responds as you intend for different screen sizes and orientations.

      Autoconnect is a separate feature that is either on or off. When turned on, it automatically creates two or more constraints for each view as you add them to the layout, but only when appropriate to constrain the view to the parent layout. Autoconnect does not create constraints to other views in the layout.

      Autoconnect is disabled by default. You can enable it by clicking Turn on Autoconnect in the Layout Editor toolbar.

      why android studio show error of «Missing constraints in constraintlayout»?

      The layout editor allows you to place widgets anywhere on the canvas, and it records the current position with design time attributes (such as layout_editor_absolute X.) These attributes are not applied at run time, so if you push your layout on a device, the widgets may appear in a different location than shown in the editor. To fix this, make sure a widget has both horizontal and vertical constraints by dragging from the edge connections

You are using in support for ConstraintLayout, if you do not add restrictions, when you start your application, all views will move to the 0.0 coordinate (high right view).

You have two options:

  • Add restrictions to your views.

  • Change in your layout ConstraintLayout by another layout for example LinearLayout or RelativeLayout.

Check these related questions:

https://es.stackoverflow.com/questions/57616/elementos-amontonados-android-studio/57785#57785

https://es.stackoverflow.com/questions/56352/es-posible-agregar-un-linearlayout-en-un-constraintlayout-o-cualquier-otro-layo/56937#56937

https://es.stackoverflow.com/questions/71634/como-manejar-la-alineaci%C3%B3n-de-elementos-view-en-constraint-layout/71636#71636


About ConstraintLayoutI recommend reading first
https://developer.android.com/training/constraint-layout/index.html

As an example a layot containing 2 views (buttons):

<Button
    android:id="@+id/Boton1"
    android:layout_width="0dp"
    android:layout_height="56dp"
    android:text="Entrada"
    android:textSize="30sp" />

<Button
android:id="@+id/Boton2"
android:layout_width="147dp"
android:layout_height="56dp"
android:text="Boton 2"
android:textSize="30sp" />

Then you can add a margin for example left (left) and top (up) to position the buttons, this is done by clicking and dragging some of the green circles that is on the left, right, up and down the view.

introducir la descripción de la imagen aquí

you would get a layout similar to:

<?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="com.example.pedro.botones.Botones">
&lt;Button
    android:id="@+id/Boton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Boton 1"
    android:textSize="30sp"
    android:layout_marginLeft="119dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="49dp" /&gt;

&lt;Button
    android:id="@+id/Boton2"
    android:layout_width="wrap_content"
    android:layout_height="56dp"
    android:text="Boton 2"
    android:textSize="30sp"
    android:layout_marginLeft="119dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="206dp" /&gt;

</android.support.constraint.ConstraintLayout>

When you run your app you can see the buttons according to the positions you defined in the elements within the ConstraintLayout. It is important to read the theory and use of the tool.

Making Sense of Auto Layout Series
Chapter 1 / Chapter 2 / Chapter 3 / Chapter 4 / Chapter 5 / Chapter 6

This is the third part of Making Sense of Auto Layout Series.

Previously, we have explained how Auto Layout calculates view position and size. In this post we will look into why Xcode shows you red lines when designing layout and how to solve them.

Xcode shows you red line in the Interface Builder (the place where you drag and drop view controller in storyboard) when it doesn’t know where it should place the view or/and what size is the view.

Lets use a simple example :

Only Width and Height constraints defined

The gray view has 2 constraints placed :

  1. Width is 240
  2. Height is 120

The size of it is defined but there is red line surrounding it, it means that Auto Layout Engine doesn’t know where to position it. We can troubleshoot what are the missing constraints by clicking the white arrow icon inside red circle button :

Show missing constraints

When you click on the missing constraints error, it will highlight the view that has missing constraint on Xcode.

Missing constraints for X, Y position

You will see that Xcode complain that it needs constraints that allow it to calculate the X position and Y position of the view. Remember Auto Layout Engine needs to know / able to calculate a view X position, Y position, width and height to render it correctly?

But there is no constraint that can let the Auto Layout Engine calculate the X position and Y position. Thats why Xcode surrounded the view with red lines to get your attention (oh you) to fix it.

There’s many way to fix it (refer to examples in this post), the simplest way to fix it is adding a top and left constraint like this :

Add Top left constraint

After adding constraint, you will see those red line changed into blue line because Xcode now know where to position the view, yay!
Blue Line Yay

Auto Layout Engine now know that the view X position is 40, Y position is 40, width is 240 and height is 120. Hence it will render it nicely across devices like this :

Looks nice in both iPhone SE and 8 yay

Summary

The example only used 1 view and I know that your app will surely have more than 1 view, but the cause of Xcode showing you red lines will always be that Xcode / Auto Layout Engine doesn’t know what size is your view or where to place your view.

Always add enough constraints to all the views so Xcode / Auto Layout Engine can know or able to calculate what size is your view and where to place your view.

In the next post, we will look into how to solve conflicting constraints (when Xcode show you red lines with numbers around your view).


Can’t wrap your head around Auto Layout and want to strangle it because it made your UI look like a mess? Check out Making Sense of Auto Layout book + case study!

“dude… wow… good job on this Auto Layout book! One of the best explanations I’ve read!” – Alex Kluew

Homework exercise

I have prepared a Xcode project with some missing constraint, you can download it here.

This project contain only one view controller in the storyboard, like this :
Exercise

There are three views and all of them have some constraints missing, your task is to add those missing constraints so that they look like this in iPhone SE, iPhone 8 and iPhone 8 plus :

Multiple screen size

Tips :
You can view the layout for all of these devices (iPhone SE, 8 and 8 plus) in Xcode without running it in Simulator. You can add a preview view like this :

Open Assistant View

Select Preview View

In the preview view, click the + button on the bottom left to add device :
Add Devices

You can check the answer of this exercise here, be sure to attempt it first before checking answer!


Tired of fighting with Auto Layout constraints? Why is it so hard to make a layout to work?! Would using code for UI and constraints make it easier? (No, not really)

If you want to understand Auto Layout fundamentally (instead of just following youtube tutorials implementing a very specific layout which might not apply to your app), check out my book Making Sense of Auto Layout, with practical case study!

 book

“It helped me understand how Auto Layout works fundamentally — something that I couldn’t find in any tutorial. I realized what Auto Layout needs for each view to render it correctly” – Ostik Lebyak

Понравилась статья? Поделить с друзьями:
  • Missing constraints android studio как исправить
  • Missing codepage or helper program or other error linux
  • Missing binary operator before token как исправить
  • Missing artifact error
  • Missing 1 required positional argument self python ошибка