ChatGPT解决这个技术问题 Extra ChatGPT

Differences between ConstraintLayout and RelativeLayout

I am confused about the difference between ConstraintLayout and RelativeLayout. Could someone please tell me the exact differences between them?

ConstraintLayout is mainly designed for the new programmers so that they can easily design the layout using the Visual Editor instead of building the layout with hand via XML.
@Jack definitely it also has deeper purpose for seasoned-expert devs
@MosesAprico you are right it does have that. But I think seasoned expert devs already have lot of other ways (they already know like RealtiveLayout, LinearLayout, GridLayout etc.) to get the view hierarchy they want.
@CopsOnRoad Actually you're wrong. Apple has been doing constraint layouts for 5+ years. You get responsive design to any size and don't have to write a ton of complex layouts. When you starting binding multiple views you only need 3 basic controls to create fully responsive design.

m
medavox

The intention of ConstraintLayout is to optimize and flatten the view hierarchy of your layouts by applying some rules to each view to avoid nesting.

The Rules are similar to RelativeLayout, for example setting the bottom edge to the bottom of some other view.

app:layout_constraintBottom_toBottomOf="@+id/view1"

Unlike RelativeLayout, ConstraintLayout offers a bias value that is used to position a view in terms of 0% and 100% horizontal and vertical offset relative to the handles (marked with a red circle). These percentages (and fractions) offer seamless positioning of the view across different screen densities and sizes.

app:layout_constraintHorizontal_bias="0.33" <!-- from 0.0 to 1.0 -->
app:layout_constraintVertical_bias="0.53" <!-- from 0.0 to 1.0 -->

The Baseline handle (a long pipe with rounded corners, below the circle handle) is used to align the content of the view with another view reference.

Square handles (on each corner of the view) are used to resize the view in dps.

https://i.stack.imgur.com/cC0bG.jpg

This is totally opinion based and my impression of ConstraintLayout


We can still create flatten layout using RelativeLayout that's why I'm confused where ConstraintLayout take care where RelativeLayout can't?
RelativeLayout is a two-pass layout, suffering from double taxation. It must measure/layout at least twice. ConstraintLayout doesn't suffer this performance penalty.
@Nothing Yep, we can still create flatten layout using RelativeLayout. But in addition to everyone mentioned here, ConstraintLayout lets you use negative margins and size subviews in predefined ratio. Last one is the most robust way to keep 16:9 ratio for your ImageView in CardView in accordance with Material design
There are some layouts that are impossible in RelativeLayout unless you nest a LinearLayout or another RelativeLayout. For example: centering a "stack" of 3 Views vertically relative to another View
@Gak2 I can't see anything impossible in your example without a nested layout. Maybe you mean something else with "stack" than I do. I just use "layout_alignEnd", "layout_below", "layout_..." and can build any kind of stack with it...
N
Naimatullah

Relative Layout and Constraint Layout equivalent properties

https://i.stack.imgur.com/ainDj.png

(1) Relative Layout:

android:layout_centerInParent="true"    

(1) Constraint Layout equivalent :

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"

(2) Relative Layout:

android:layout_centerHorizontal="true"

(2) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintEnd_toEndOf="parent"

(3) Relative Layout:

android:layout_centerVertical="true"    

(3) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent"

(4) Relative Layout:

android:layout_alignParentLeft="true"   

(4) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="parent"

(5) Relative Layout:

android:layout_alignParentStart="true"

(5) Constraint Layout equivalent:

app:layout_constraintStart_toStartOf="parent"

(6) Relative Layout:

android:layout_alignParentRight="true"

(6) Constraint Layout equivalent:

app:layout_constraintRight_toRightOf="parent"

(7) Relative Layout:

android:layout_alignParentEnd="true"    

(7) Constraint Layout equivalent:

app:layout_constraintEnd_toEndOf="parent"

(8) Relative Layout:

android:layout_alignParentTop="true"

(8) Constraint Layout equivalent:

app:layout_constraintTop_toTopOf="parent"

(9) Relative Layout:

android:layout_alignParentBottom="true" 

(9) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="parent"

(10) Relative Layout:

android:layout_alignStart="@id/view"

(10) Constraint Layout equivalent:

app:layout_constraintStart_toStartOf="@id/view"

(11) Relative Layout:

android:layout_alignLeft="@id/view" 

(11) Constraint Layout equivalent:

app:layout_constraintLeft_toLeftOf="@id/view"

(12) Relative Layout:

android:layout_alignEnd="@id/view"  

(12) Constraint Layout equivalent:

app:layout_constraintEnd_toEndOf="@id/view"

(13) Relative Layout:

android:layout_alignRight="@id/view"

(13) Constraint Layout equivalent:

app:layout_constraintRight_toRightOf="@id/view"

(14) Relative Layout:

android:layout_alignTop="@id/view"  

(14) Constraint Layout equivalent:

app:layout_constraintTop_toTopOf="@id/view"

(15) Relative Layout:

android:layout_alignBaseline="@id/view" 

(15) Constraint Layout equivalent:

app:layout_constraintBaseline_toBaselineOf="@id/view"

(16) Relative Layout:

android:layout_alignBottom="@id/view"

(16) Constraint Layout equivalent:

app:layout_constraintBottom_toBottomOf="@id/view"

(17) Relative Layout:

android:layout_toStartOf="@id/view"

(17) Constraint Layout equivalent:

app:layout_constraintEnd_toStartOf="@id/view"

(18) Relative Layout:

android:layout_toLeftOf="@id/view"  

(18) Constraint Layout equivalent:

app:layout_constraintRight_toLeftOf="@id/view"

(19) Relative Layout:

android:layout_toEndOf="@id/view"

(19) Constraint Layout equivalent:

app:layout_constraintStart_toEndOf="@id/view"

(20) Relative Layout:

android:layout_toRightOf="@id/view"

(20) Constraint Layout equivalent:

app:layout_constraintLeft_toRightOf="@id/view"

(21) Relative Layout:

android:layout_above="@id/view" 

(21) Constraint Layout equivalent:

app:layout_constraintBottom_toTopOf="@id/view"

(22) Relative Layout:

android:layout_below="@id/view" 

(22) Constraint Layout equivalent:

app:layout_constraintTop_toBottomOf="@id/view"


Can you post as text instead of image? So that it will be very useful to me and also others in future.
Everybody beginning to learn Constraint Layouts needs to see this. Thanks.
This is useful information, but is simply a documentation dump and doesn't do anything to explain the difference between them.
No, I dont have time to look in docs, this is certainly useful. And written in simple language. Upvoting.
M
Mike

Reported by @davidpbr ConstraintLayout performance

I made two similar 7-child layouts, one each with a parent ConstraintLayout and RelativeLayout. Based on Android Studio method tracing tool, it appears the ConstraintLayout spends more time in onMeasure and performs additional work in onFinishInflate.

Library used (support-v4, appcompat-v7…):

com.android.support.constraint:constraint-layout:1.0.0-alpha1

Devices/Android versions reproduced on: Samsung Galaxy S6 (SM-G920A. Sorry, no Nexus atm). Android 5.0.2

Quick method tracing comparison:

https://i.imgur.com/6OCCCvK.png

Sample Github repo: https://github.com/OnlyInAmerica/ConstraintLayoutPerf


from the same issue: I'm going to close this for now -- alpha 4/5 brought quite a bit of performance improvement. We'll probably be able to improve it more, but that might wait post 1.0.
@Nativ Monotirs->CPU->Time tracker icon
Run and profiled same code on with constraint-layout:1.0.1 on Nexus 5 with android 6.0.1, here results: Relative layout - init 2ms on Measure 30ms + 16ms = 62ms on Layouyt 7ms = 9ms total 54 ms Constraint Layout - init 7ms Constraint Layout generate layout params + add view ~ 7*2ms = 14ms On Measure 60ms + 52ms ~ 112ms On Layout 8ms total ~ 141ms First initialization of Relative layout almost three times faster than Constraint.
Constraint Layout is introduced so that the nested view hierarchy can be reduced. So, Less hierarchy means less time to traverse from top to down in the view tree. So, What's the Point to make a nested view hierarchy that may not be needed in Constraint layout and comparing it with Relative Layout in which you have more chances to end up with nested structure?
This is valuable information, but does not answer the question. Nor does it even address the question.
L
Lii

Following are the differences/advantages:

Constraint Layout has dual power of both Relative Layout as well as Linear layout: Set relative positions of views ( like Relative layout ) and also set weights for dynamic UI (which was only possible in Linear Layout). A very powerful use is grouping of elements by forming a chain. This way we can form a group of views which as a whole can be placed in a desired way without adding another layer of hierarchy just to form another group of views. In addition to weights, we can apply horizontal and vertical bias which is nothing but the percentage of displacement from the centre. ( bias of 0.5 means centrally aligned. Any value less or more means corresponding movement in the respective direction ) . Another very important feature is that it respects and provides the functionality to handle the GONE views so that layouts do not break if some view is set to GONE through java code. More can be found here: https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#VisibilityBehavior Provides power of automatic constraint applying by the use of Blue print and Visual Editor tool which makes it easy to design a page.

All these features lead to flattening of the view hierarchy which improves performance and also helps in making responsive and dynamic UI which can more easily adapt to different screen size and density.

Here is the best place to learn quickly: https://codelabs.developers.google.com/codelabs/constraint-layout/#0


6) ConstraintLayout makes it possible to size subviews in pre-defined ratios medium.com/google-developers/…. It'd useful for example when you're going to keep your ImageView in 16:9.
H
Herrbert74

A big difference is that ConstraintLayout respects constraints even if the view is gone. So it won't break the layout if you have a chain and you want to make a view disappear in the middle.


can you give me any example? let suppose 3 buttons are there. I will hide the 2nd button and the 3rd button is attach to 2nd button with the id as btn2. Suppose I hide 2nd button then how 3rd button could find the 2nd button's id?
That's not true. If you set the visibility of a Button as "INVISIBLE" instead of "GONE" you won't break the constraints. As for me, the biggest different as @Nikola said is the bias which helps you create more "Responsive" views.
@Nothing Let's suppose that the buttons are under each other. Even if you hide tButton 2, it's still there in the "view contract", either in your xml or code. ConstraintLayout will respect it and Button 3 will be under Button 1. In a RelativeLayout Button 2 is gone, the contraint is gone with it, so Button 3 will be in the default position, so top left of the screen.
@zapotec I respect that other stuff is more important to you, but for me this is a really cool difference. Fixes the only thing I hated in RelativeLayout. Using invisible is not an option, because it will claim the space.
s
serv-inc

Officially, ConstraintLayout is much faster

In the N release of Android, the ConstraintLayout class provides similar functionality to RelativeLayout, but at a significantly lower cost.


m
murali kurapati

The Conclusion I can make is

1) We can do UI design without touching the xml part of code, to be honest I feel google has copied how UI is designed in iOS apps, it will make sense if you are familiar with UI development in iOS, but in relative layout its hard to set the constraints without touching the xml design.

2) Secondly it has flat view hierarchy unlike other layouts, so does better performance than relative layout which you might have seen from other answers

3) It also have extra things apart from what relative layout has, such as circular relative positioning where we can position another view relative to this one at certain radius with certain angle which cant do in relative layout

I am saying it again, designing UI using constraint layout is same as designing UI in iOS, so in future if you work on iOS you will find it easier if you have used constraint layout


A
Andrey T

In addition to @dhaval-jivani answer.

I've updated the project github project to latest version of constraint layout v.1.1.0-beta3

I've measured and compared the time of onCreate method and time between a start of onCreate and end of execution of last preformDraw method which visible in CPU monitor. All test were done on Samsung S5 mini with android 6.0.1 Here results:

Fresh start (first screen opening after application launch)

Relative Layout

OnCreate: 123ms

Last preformDraw time - OnCreate time: 311.3ms

Constraint Layout

OnCreate: 120.3ms

Last preformDraw time - OnCreate time: 310ms

Besides that, I've checked performance test from this article , here the code and found that on loop counts less than 100 constraint layout variant is faster during execution of inflating, measure, and layout then variants with Relative Layout. And on old Android devices, like Samsung S3 with Android 4.3, the difference is bigger.

As a conclusion I agree with comments from the article:

Does it worth to refactor old views switch on it from RelativeLayout or LinearLayout? As always: It depends 🙂 I wouldn’t refactor anything unless you either have a performance problem with your current layout hierarchy or you want to make significant changes to the layout anyway. Though I haven’t measured it lately, I haven’t found any performance issues in the last releases. So I think you should be safe to use it. but – as I’v said – don’t just migrate for the sake of migrating. Only do so, if there’s a need for and benefit from it. For new layouts, though, I nearly always use ConstraintLayout. It’s so much better compare to what we had before.


M
Mike

The real question to ask is, is there any reason to use any layout other than a constraint layout? I believe the answer might be no.

To those insisting they are aimed at novice programmers or the like, they should provide some reason for them to be inferior to any other layout.

Constraints layouts are better in every way (They do cost like 150k in APK size.). They are faster, they are easier, they are more flexible, they react better to changes, they fix the problems when items go away, they conform better to radically different screen types and they don't use a bunch of nested loop with that long drawn out tree structure for everything. You can put anything anywhere, with respect to anything, anywhere.

They were a bit screwy back in mid 2016, where the visual layout editor just wasn't good enough, but they are to the point that if you are having a layout at all, you might want to seriously consider using a constraint layout, even when it does the same thing as a RelativeLayout, or even a simple LinearLayout. FrameLayouts clearly still have their purpose. But, I can't see building anything else at this point. If they started with this they wouldn't have added anything else.


Is there any proof it faster?
Yes. It's faster. The layout is down in a single solver rather than iterating through a tree. For most things it won't matter because it's done at the call to the layout. But, the view tree thing while easy, creates a bunch of views inside views which requires calls requiring calls. While it's nicer theoretically, in practice performing the layout in one bit of code is far easier than to iterate through the entire view tree. It would get more impressive with more views but here's a benchmark from May: medium.com/@krpiotrek/constraintlayout-performance-c1455c7984d7
I am facing another question, should I replace all existing Relativelayouts in the app I am working on? Will it significantly improve performance?
@SreekanthKarumanaghat it seems like you'd never make back the time it takes to replace those back in the time switching would save you. We're talking 3.5ms cycles dropping to 3.25ms in most cases. If it gives you an extra feature or something you need then sure, but purely on speed grounds nah. Though we are talking hitting a convert button.
W
Wilson

The only difference i've noted is that things set in a relative layout via drag and drop automatically have their dimensions relative to other elements inferred, so when you run the app what you see is what you get. However in the constraint layout even if you drag and drop an element in the design view, when you run the app things may be shifted around. This can easily be fixed by manually setting the constraints or, a more risky move being to right click the element in the component tree, selecting the constraint layout sub menu, then clicking 'infer constraints'. Hope this helps