Перейти к содержимому

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

  • автор:

Проблема с ConstraintLayout

Недавно начал изучать Android Studio, наткнулся на проблему. Когда я хочу добавить текст, кнопку и т.д на девайс, добавленные компоненты пропадают за экран телефона. Затем выводится ошибка: 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. Я перевел, но так и не смог решить проблему.

Отслеживать
задан 28 июн 2018 в 13:52
101 2 2 золотых знака 2 2 серебряных знака 11 11 бронзовых знаков

2 ответа 2

Сортировка: Сброс на вариант по умолчанию

ConstraintLayout требует подробной настройки расположения элементов основываясь на констреинтах (взаимном положении и т.д.) — он как продвинутый RelativeLayout .

Констреинты примерно означают «настройки положения вью» — куда должны «притягиваться» верх/низ и т.д., какой и где марджин, нужно ли как-то взаимодействовать с гайдлайнами.

В интернете информации более чем достаточно — читайте или официальную доку, или статейки вроде этой (первая попавшаяся в гугле, вроде бы неплохо написана).

Ошибка говорит вам:

This view is not constrained. It only has designtime positions, so it will jump to (0,0) at runtime unless you add the constraints

У вашего вью не настроены констреинты. Он имеет только настройку отображения в визуальном редакторе, а в рантайме (на устройстве) он прыгнет в точку (0, 0).

Также в редакторе есть магическая кнопочка (но помогает она не всегда, лучше вручную):

введите сюда описание изображения

Она на основе того, как вы расположили в редакторе элементы, постарается настроить констреинты (правда, с кучей лишних марджинов и всего такого) вместо вас.

Как исправить ошибку в 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.

  • Вопрос задан более трёх лет назад
  • 3603 просмотра

1 комментарий

Средний 1 комментарий

Fix android studio missing constraints in constraintlayout error

Иконка канала Кotlin Разработка интернета вещей

his 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. Issue id: MissingConstraints Vendor: Android Open Source Project Contact: https://groups.google.com/g/lint-dev Feedback: https://issuetracker.google.com/issues/new?component=192708

Показать больше

Войдите , чтобы оставлять комментарии

Why missing constraints appear and how to solve them

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

Blue Line Yay

After adding constraint, you will see those red line changed into blue line because Xcode now know where to position the view, 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.

Exercise

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

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

Add Devices

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

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

Afraid that you might not be able to implement Sign in with Apple in time and get rejected? (deadline is 30th June). Wouldn’t it be good to have a step by step tutorial that guide you on how to exchange authorization Code , decode identity token, generate client secret and finally authenticate the user? Plus you can implement it within a day , check out my book Practical Sign in with Apple , with Ruby / Python / PHP / NodeJS code samples that you can directly plug in!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *