قالب وردپرس درنا توس
Home / IOS Development / ConstraintLayout Android Tutorial: Complex Layouts

ConstraintLayout Android Tutorial: Complex Layouts



ConstraintLayout is a setup on Android that gives you customizable and flexible ways to create impressions for your apps.

ConstraintLayout which is now the default setup in Android Studio, gives you many ways to place objects. You can limit them to the container, to each other or to guidelines. This allows you to create large, complex, dynamic and responsive views in a flat hierarchy. It even supports animations!

In this tutorial, you learn to use a variety of ConstraintLayout features by building an app for a travel agent. In the process, you learn how to:

  • Convert from other types of layouts to ConstraintLayout .
  • Dynamic place UI elements on the screen relative to other elements.
  • Animate your views.

Raze Galactic ̵
1; An Intergalactic Travel Service

During this tutorial you will build an interface for an intergalactic travel program that allows users to book trips between planets, schedule weekend airport stations and make reservations for moon rover to get around when
  Change project animated

Getting Started

Use Download Materials button at the top or bottom of this tutorial to download the start project.

Open the startup package project in Android Studio. Build and run the app.
  startup project running

There are many items in this app. You learn how to properly display them using a complex ConstraintLayout in this tutorial.

To start, go to Android Studio and open the layout file for this app, activity_main.xml in design view. Notice the structure of the layout is a series encapsulated LinearLayout s and RelativeLayout s.
  Sacred Nested Layouts, Batman!

ConstraintLayout is not the best choice for simple layouts, but it is great for complex layouts like that in this tutorial.

Convert a layout to ConstraintLayout

In Component Tree in design view, right click on top level LinearLayout and select Convert LinearLayout to ConstraintLayout from the context menu: [19659020] convert linear layout to constraint setup ” width=”650″ height=”457″ class=”aligncenter bordered size-large wp-image-214340″ srcset=”https://koenig-media.raywenderlich.com/uploads/2019/01/convert_layout-650×457.png 650w, https://koenig-media.raywenderlich.com/uploads/2019/01/convert_layout-455×320.png 455w” sizes=”(max-width: 650px) 100vw, 650px”/>

Next, get a pop-up dialog with some options:
  conversion option dialog

Accept the default values ​​after reading what they do and click OK to reject the dialog and convert the setup. Android Studio will then attempt to remove all nested layouts and convert the setup to ConstraintLayout .

At this time, you may need to give Android Studio a moment to do some processing as it tries to figure out the new setup. After a moment the layout may look like this:
  intermediate layout

After a moment, all your views can only jump into the upper left corner of the layout. If this happens, don't panic!

Note : Be sure to turn off Autoconnect for this tutorial. Find this option in the design editor toolbar after selecting ConstraintLayout .
  turn off autoconnect

Remove outdated limitations

During the conversion process, Android Studio performs a number of steps. The last may have been Infer Constraints whose results could not be what you wanted. ;] If so, simply go to Edit menu and select Undo Infer Restrictions :
  Undo Infer Restrictions
Alternatively, just press Z -Z on Mac or Control-Z on Windows.

In the Android Studio design view, your preview may now look like this:
  after deleting inferior constraints

It's close, but not quite where the layout needs to be. You can drag the views around a bit until they look more like the original layout:
  original layout

Note : This tutorial uses a Pixel 2 as the device in the preview. If you use a different device, the views may look different than they do on the screens. You can change this setting in the toolbar.

 design editing device control

Don't spend much time trying to get the setup just as it was before. At this point you will only have a very rough estimation to get you visually oriented. You add all the limitations you need to make it look perfect in the rest of this tutorial.

When done, your layout may look like this:
  rough layout

If Android Studio added some restrictions automatically as you drag the views around, just click Clear All Constraints button to get rid of them.
  clear all limitations

One last thing before adding these items to their final places, change ID of the root ConstraintLayout to be limitationLayout .

Resize images

Next, fix the image sizes by clicking on each of the icons, spaceStationIcon flightsIcon ] and roverIcon on the top. Then change layout_width and layout_height properties from wrap_content to 30dp.
<img src = "https://koenig-media.raywenderlich.com/uploads/2019/01/width-height-attributes-650×281.png" alt = "width and height attributes in Attributes 19659048] You see a number of errors listed in Component Tree which are shown because Android does not have any limitations information to tell you where to place the user interface elements. 19659027] Note : Android Studio offers various ConstraintLayout tools to save time, but they do not always do what you expect, it helps to visualize what the restrictions should do before you start adding them. the way, if Android Studio's tools discomfort, you can add individual limitations one at a time to achieve the effect you want.

Remember to use Adjust the menu and other tools in the steps below: If Android Studio does not work For what you expect, go back and add your individual limitations yourself.

Adding Restrictions: Finding Adjustment

You want to set your limitations with a top-down approach, starting with the items at the top of the screen, and working your way down to the bottom.

You want the three icons at the top of the screen to stand up with each other horizontally. Then you place the labels under each of these icons.

Restriction of the first icon

First, you want to limit spaceStationIcon over the word "Space Stations" at the top of the screen.

To do this, click spaceStationIcon to select it and reveal restriction anchors. Click the top anchor and drag it to the top of the view. The icon can slide up to the top of the view. Do not connect the left boundary yet.

With spaceStationIcon ] selected, drag it down from the top so that there is some space between the top of the display and the rocket.

Next, switch to Code View and examine the updated XML for the rocket icon. You added a new restriction, app: layout_constraintTop_toTopOf = "parent" and a top margin attribute for the space between the rocket and the top of the view. Update the code to set the margin to 15 dp.

XML for spaceStationIcon should now look like this:


You can also adjust the margin in the design view. To do this, switch to Design View and click the Attributes tab to the right if it is not already visible.

Then click spaceStationIcon to reveal the attributes of the image. After ID layout_width and layout_height you see a graphical representation of the margins.

You can select a new value for the margin by selecting it from the drop-down menu or by clicking on the number and entering a new value.
  marginal attribute

Adjusting the three top icons horizontally: Using chains

Then you want the three icons at the top of the screen to line up on a row of equal spaces between them. To achieve this, you can add a number of individual limitations to each icon. However, there is a much faster way to do this using chains .

Chains

A chain occurs when you have two-way restrictions. You will not necessarily see anything special in XML; The fact that there are common constraints in XML is enough to make a chain.

When using adjustment controls from the menu, such as Adjust Horizontal Centers Android Studio actually uses a chain. You can use different styles, weights and margins for chains.

Start by switching back to Design view. Shift-click to select all three icons at the top of the screen: spaceStationIcon flightsIcon and roverIcon . Right-click to retrieve the context menu and select Center alt Horizontal . This will automatically create a chain and generate constraints.

In the design view you can see that some of the lines representing the constraints look different from others. Some look like sharp lines, while others look like a chain.
  chains

Exploring chains

To explore some of chain modes click on the Cycle Chain Mode button that appears at the bottom of the icons when you select them.
  cycle chain mode

The modes are:

  • Packed : The items are displayed packed together.
  • Spread : The elements spread over free space, as shown above.
  • Scattered inside : Similar to spreading, but the end points of the chain are not spread out.

  Chain Mode

Make sure you exit with spread as the selected chain mode. You want to know that this is selected in two ways:

  1. The display will appear with the icons placed as they are on the screen, for example
  2. The attribute app: layout_constraintHorizontal_chainStyle = "spread" turns on one of image views. Updating this attribute is another way to change the chain mode.

Adjustment views

Again, select the three icons. From the toolbar, select Adjust ▸ Vertical Centers . Android Studio should add limitations to the images to adjust the bottom and top of each image to the neighbor.

 adjust vertical centers

Your layout should now look like this:
  adjusted icons

If your layout does not match this image, you can see text and design the views. If you have lost the original restriction between flightsIcon and the top of the view, and if spaceStationIcon did not get the limitations you expected, press ⌘ + Z ] on Mac, or Control + Z on Windows to undo.

Then manually place the restrictions by clicking on the upper bounding anchor on spaceStationIcon and dragging it to the upper bounding anchor on flightsIcon and so on until you have added all of the limitations in the diagram above.

Your three icons should now have the following XML:






Adjust the text for each of the icons

Now that the icons are in place, you need to set their text fields to appear in their correct locations.

Select TextView labeled Space Stations to reveal its boundary anchor. Limit the left side of the space stations TextView to the left of the space station icon and to the right of Space Stations TextView to the right of the space station icon. This centers it vertically with the icon.

Then change the default margins in the toolbar to 15dp, and just drag from the top anchor to the label of the bottom anchor on the icon, which will set both the limit and margin in a single step. Do the same for the other labels to adjust them to their icons.

 labels animation

Now, the limitation errors for the two top rows of the UI elements should be gone. XML for the three top images and labels should look like this:






Using Guidelines

So far, you have limited user interfaces to their parent containers and to each other. Another option you have is to add invisible guidelines to the layout and limit the user interface elements to these guidelines.

Remember that in the final layout, the double arrows should be centered and should overlap the two green views.
  overlapping views

Set horizontal and vertical guidelines

Select the double arrow icon and set height and width to 60 dp. Then right-click on it and select Center ▸ Horizontal in Parents from the context menu.
  Double Arrows Center
For each of the green TextView s, you will now enter the width to 124dp and the height to 98dp.

To get the dual pilot icon to overlap the two green TextView s, you will limit the right side to the left TextView ] to the right of the double arrow icon and set the right margin to 40dp.

Likewise, the left side of the right restricts Text display to the left of the double arrow icon and set to the left margin to 40dp.

Finally, you limit the top and bottom of TextView s to the top and bottom of doubleArrowsIcon .
  Overlapping Views
Next, click Guidelines in the toolbar and select Add Horizontal Guideline .
  add horizon number guideline

This will add a horizontal line to the layout.

Select the horizontal guideline using Component Tree in Design View. In the attributes of the inspector, change ID into the guidelines of guideline1 . Notice the Policy Properties: layout_constraintGuide_begin and layout_constraintGuide_percent .

For the horizontal guideline, set layout_constraintGuide_begin to 200dp.
  horizontal guideline 200dp [19659003] Finally, add a vertical guideline, make sure you have set ID to guideline2 and set layout_constraintGuide_percent layout_constraintGuide_percent to 0.05.

Positioning Guidelines

You can place guidelines using one of these three attributes:

  • layout_constraintGuide_begin : position a guide with a specific number of dp from the left (for vertical guides) or the top (for horizontal guides) of their superior.
  • layout_constraintGuide_end : positions a guide a specific number of dp from the right or bottom of its parent.
  • layout_constraintGuide_percent : places a guideline in percent of the width or height of the parents.

When limiting items to the guidelines, you can limit other items to them. In this way, if the policy changes position, anything that is limited to the policy or to the other elements set out in the policy will adjust the position.

Hint : Later, use this feature to create some cool animations!

Adding Restrictions to Policies

Now that your policies are set up, you can start adding restrictions to them.

] First, for the double arrow icon:

  • Limit the bottom of the horizontal guide.
  • Set the bottom margin to 40dp.

For the switch:

  • Set the width to 160dp.
  • Limit the left side to the vertical guideline.
  • Limit the parent's top (at the top of the screen).
  • Set the margin at the top to 200 dp.

For the label under the switch listed number of travelers:

  • Limit the left side to the vertical guideline.
  • Limit the top to the bottom of the switch.

For the galaxy icon (id is galaxyIcon ):

  • Set the width and height to 90 dp.
  • Limit the top to horizontal guideline.
  • Limit the bottom to the bottom of the parents (bottom of the screen). This shows it between the horizontal guideline and the bottom of the screen.
  • Center it horizontally in the main view.

For the rocket icon to the left of the galaxy icon (ID is rocketIcon ):

  • Set the width and height to 30dp.
  • Limit the rocket icon's top, bottom and right sides to the top, bottom, and left side of the galaxy icon, respectively.

Finally, for the DEPART button at the bottom:

  • Change the width from wrap_content to match_parent .
  • Limit the bottom to the bottom of the parents (bottom of the screen).

At this time, you should have set all the restrictions that Android Studio needs to figure out the setup; There should be no errors in the component tree. Your layout should now look like this:
  Final static layout

Build and run the app:
  Final static layout in emulator

Your layout looks great now! But clicking on the button does nothing … so it's time to add some pizzaz with a few simple animations!

Circular Position Guidelines

In addition to the methods you have already learned, you can also limit UI elements to each other by using distance and angle. This allows you to place them on a circle, where one UI element is in the center of the circle and the other is on the circumference.

 circular limitations

To do this, select the rocket icon next to the galaxy icon and update the code in Code View as follows:


The first limitation attribute, layout_constraintCircle indicates ID of the user interface element that will be at the center of the center. The other two attributes indicate the angle and radius.

Why do you want to use such an unusual type of restriction, you ask? Stay up-to-date, for a moment you will use this technique to animate the rocket to fly around the screen!

Note : You can ignore the error in Component Tree for the display using circular restriction. Android Studio doesn't seem to recognize circular constraints yet.

Build and run the app. Everything should still be displayed properly positioned on the screen:
  circular constraint

Animating the UI elements on the screen

Now that you are a master to put things on the screen using ConstraintLayout It's time to add some rocket fuel to the mix and move on to the next level!

In this section, you begin with the complex layout you created and add some cool UI animations in just a few steps.

Limit sets

Using ConstraintLayout s, you can use Keyframe Animations to animate your views. To do this, you will enter a scroll-down copy of your layout file, known as a ConstraintSet . A ConstraintSet only needs to contain limitations, margins and padding of the elements of a given ConstraintLayout .

In the Kotlin code, you can then use ConstraintSet to ConstraintLayout to update the setup.

To build an animation, you need to specify a single layout file and a ConstraintSet to act as the start and end keyframes. You can also use transitions to make the animations a little more advanced.

Configure start layout for your animation

In your project, duplicate your layout file and the name of the duplicate keyframe1.xml . You need to change the locations of the items in this new setup and set this new layout as the start layout for the app.

To start, open keyframe1.xml and change ] layout_constraintGuide_begin the property of guideline1 from 200dp to 0dp. This moves the wizard, the items limited to the wizard, and all items limited to them higher up, so that some of them are now out of focus.

Then change the layout_constraintGuide_percent property of guideline2 from .05 to 1. This moves the wizard and the items confined to it to the far right so that they are also shielded.

Now we have changed the layout by just moving a few guides, but we still need to make this new layout the basic design for the app. To do this, open MainActivity.kt and modify the setContentView () call in the onCreate () function to pass in R.layout.keyframe1 instead of R.layout.activity_main :

  setContentView (R.layout.keyframe1)

Build and run your app. The orange switch and the label and the arrival and destination slot openings are no longer displayed on the screen. In addition, the rocket and universe icons have moved up:
  modified guidelines

Animate the view

Change the following import task in MainActivity.kt Kotlin class:

  import import kotlinx.android.synthetic.main.activity_main. *

to the following:

  Import kotlinx.android.synthetic.main.keyframe1. *

This allows you to refer to interface elements in the new layout XML without any findViewById () madness from the prehistoric days of Android development. :]

Then add the following private properties in the class. You may need to add android.support.constraint.ConstraintSet import:

  private select constraintSet1 = ConstraintSet ()
private val constraintSet2 = ConstraintSet ()

private was isOffscreen = true

The first two properties are the restriction sets you want to use to animate your view. You want to use Boolean to keep track of the setup status.

Transition Manager

You can use the class Transition Manager to handle transition from one keyframe to another. To create a layout animation, you simply give transition handles with ConstraintSet you want to animate, and it will handle the rest. Alternatively, you can provide the custom animations to perform.

Now add the following in the onCreate () function and import TransitionManager :

  constraintSet1.clone (constraintLayout) // 1
constraintSet2.clone (this, R.layout.activity_main) // 2

departButton.setOnClickListener {// 3
// use the transition
TransitionManager.beginDelayedTransition (constraintLayout) // 4
selection restriction = if (! isOffscreen) constraintSet 1 other constraintSet2
isOffscreen =! isOffscreen
constraint.applyTo (constraintLayout) // 5
}
  1. This draws the layout information from the original layout to one of the constraint sets, constraintSet1 . Since you added a ID to ConstraintLayout earlier, you can refer directly to the code now.
  2. This draws the layout information from the final layout to constraintSet2 . Since you create a ConstraintSet and you never inflate the second layout file, you avoid overhead and performance traits to handle a second layout.
  3. This adds the animation to the listener for the button, so you can trigger the animation when it is switched.
  4. This is called Transition Manager's beingDelayedTransition function.
  5. This applies to the new ConstraintSet to the current view ] ConstraintLayout .

Build and run the app. Click the button at the bottom of the screen to see how the animation works.

Voila! The app loads with a multitude of elements offscreen. When you press the button, the controls control which causes everything to be limited to them to animate as well.
  guidelines animated

Animating the boundaries of a view

Not only can you change the position of items on the screen by affecting their limitations, but you can also change their size.

Open keyframe1.xml and select the galaxy icon whose ID is galaxyIcon . Change the property layout_height from 90dp to 10dp.

Note : In activity_main.xml the height is still set to 90dp.

Build and run the app and press the button at the bottom of the button at the bottom. Now you can experience the expansion of the galaxy in action! :]
  see limits animated

Using custom transitions to make animation easier

You now have a couple of animations associated with the switch, but it would not be nice for the display to animate automatically when

You will do the next, but first you will create a custom animation instead of using the default animation, and you will also customize the animation timing.

Add the following function in ] MainActivity.kt adds the import for android.transition.AutoTransition if it is not added automatically:

  overrides the fun on EnterAnimationComplete () {/ / 1
super.onEnterAnimationComplete ()

constraintSet2.clone (this, R.layout.activity_main) // 2

// use the transition
Selection transition = AutoTransition () // 3
transition.duration = 1000 // 4
TransitionManager.beginDelayedTransition (limitationLayout, transition) // 5

constraintSet2.applyTo (constraintLayout) // 6
}
  1. Activities cannot draw anything while the view is animating. onEnterAnimationComplete () is the point of the app's lifecycle where the display animation has completed and it is safe to call the drawing code.
  2. This draws the layout information from your final layout to constraintSet2 .
  3. This creates a custom transition. In this case, use a built-in transition, AutoTransition () which first disappears, disappears targets, moves and resizes existing targets, and eventually disappears in target.
  4. This sets a duration of 1000 milliseconds for the animation so that it is slow enough to be seen.
  5. This is called Transition Manager's beingDelayedTransition feature, but this time you also deliver your customized transition.
  6. This applies to the new ConstraintSet to the current ConstraintLayout .

Build and run the app. Now, all the animations happen as soon as the view loads.
  animations on cargo

Animating Circular Constraint

Remember that fun circular constraint you've added earlier? Time to add the grand final animation by flying the rocket around the galaxy!

To animate the rocket around the galaxy, you need to change two characteristics: the angle of the circular constraint, which moves the position of the rocket around the circle and rotation of the rocket to complete the illusion. You also check the One way / Round Trip switch value to determine if the rocket will fly a half circle or a full circle.

Replace the click listener for the DEPART button in onCreate () as follows:

  departButton.setOnClickListener {
// 1
choice layoutParams = rocketIcon.layoutParams as ConstraintLayout.LayoutParams
select startAngle = layoutParams.circleAngle
choice endAngle = startAngle + (if (switch1.isChecked) 360 else 180)

// 2
val anim = ValueAnimator.ofFloat (startAngle, endAngle)
anim.addUpdateListener {valueAnimator ->

// 3
falls animatedValue = valueAnimator.animatedValue as Float
choice layoutParams = rocketIcon.layoutParams as ConstraintLayout.LayoutParams
layoutParams.circleAngle = animatedValue
rocketIcon.layoutParams = layoutParams

// 4
rocketIcon.rotation = (animatedValue% 360 - 270)
}
// 5
anim.duration = if (switch1.isChecked) 2000 otherwise 1000

// 6
anim.interpolator = LinearInterpolator ()
anim.start ()
}
  1. Sett startAngle til den nåværende vinkelen på raketten før animasjonsstart. Avhengig av One Way / Round Trip bryteren, endAngle er enten 180 eller 360 grader i tillegg til startAngle verdien.
  2. ValueAnimator klassen gir en enkel timingmotor for å kjøre animasjoner mellom to verdier. Her gir du startAngle og endAngle for å lage forekomsten av ValueAnimator .
  3. Innvendig oppdateringslytter av ValueAnimator eksempel, få den animerte verdien og tilordne den til raketens circleAngle i layoutParams .
  4. Rotate the rocket with animated value. This will make the rocket fly in more natural direction.
  5. This is quite straightforward. One way animation takes 1 second, while round trip animation takes 2 seconds.
  6. Choose LinearInterpolator to make sure passengers have pleasant flight. You can try AnticipateOvershootInterpolator to see what will happen :] Last but not least, start the animation!

Build and run the app. Click the DEPART button and toggle the switch to make the rocket fly around the galaxy:
fly around the galaxy

Congratulations! You’ve built a complex UI layout for a space travel Android app, and you’ve added some cool animations to it with just a few lines of code.

Where to Go From Here?

You can download the final version of this project using the Download Materials button at the top or bottom of this tutorial.

If you enjoyed building the view animations, you might like to try the more sophisticated animation possibilities provided by MotionLayout, which is in alpha as of this writing. As always, you can also look at the documentation for ConstraintLayout.

For more on MotionLayout see this presentation: New Features in ConstraintLayout 2.0: Designing With Constraints — Sean McQuillan — Android Summit 2018 — YouTube.

Hopefully, you’ve enjoyed this tutorial. If you have any comments, feel free to hop into the forum below!


Source link