Relative Layout (상대 레이아웃)
Relative Layout(상대 레이아웃)은 다른 요소에 기반한 제약조건(Constraint)을 설정하여 요소의 위치와 크기를 더 많이 제어할 수 있는 레이아웃이다. Absolute Layout(절대 레이아웃)과 마찬가지로 여러 요소를 겹쳐서 표현할 수 있으며 Absolute Layout이 구현하지 못하는 UI도 구현이 가능하다.
지금까지 접한 레이아웃 중 가장 헷갈리는 레이아웃이다…
Relative Layout 사용 예
SNS의 사용자 프로필 중 배경이미지(배너)에 있는 프로필 사진
주요 속성들
XAML 태그 확장을 사용한다.
- RelativeLayout.WidthConstraint
- RelativeLayout.HeightConstraint
- RelativeLayout.XConstraint
- RelativeLayout.YConstraint
- RelativeLayout.BoundsConstraint
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyFirstXamarinApp.RelativePage"> <RelativeLayout> <!-- RelativeLayout.WidthConstraint 및 RelativeLayout.HeightConstraint - Type: 어떤 요소를 대상으로 상대적으로 배치할 것인가 - Property: 어떤 속성에 제약을 둘 것인가 - Factor: Property 값의 몇 배로 제약을 둘 것인가 (0 ~ 1 사이의 double 값) --> <BoxView Color="Aqua" x:Name="banner" RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1}" RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=0.3}"> </BoxView> <!-- RelativeLayout.XConstraint 및 RelativeLayout.YConstraint - Type: 어떤 요소를 대상으로 상대적으로 배치할 것인가 - ElementName: 어떤 요소를 참조할 것인가 (x:Name 값) - Property: 어떤 속성에 제약을 둘 것인가 - Factor: Property 값의 몇 배로 제약을 둘 것인가 (0 ~ 1 사이의 double 값) - Constant: Property 값을 얼만큼 조절할 것인가 (양수 또는 음수 값) --> <BoxView Color="Silver" RelativeLayout.XConstraint="{ConstraintExpression Type=RelativeToView, ElementName=banner, Property=Width, Factor=0.1}" RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView, ElementName=banner, Property=Height, Factor=1, Constant=-20}"> </BoxView> </RelativeLayout> </ContentPage>
실행결과
Relative Layout – C# (Code-Behind)
- C# 코드를 이용한 RelativeLayout 구현
using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace MyFirstXamarinApp { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class RelativePage : ContentPage { public RelativePage () { InitializeComponent (); var layout = new RelativeLayout(); Content = layout; var aquaBox = new BoxView { Color = Color.Aqua }; var silverBox = new BoxView { Color = Color.Silver }; /* Add() 메소드는 여러 오버로딩이 존재 * 첫번째 매개변수: 추가할 요소 * 두 번째 매개변수부터는 명명된 매개변수(Named Parameter)를 사용하여 제약조건 설정 */ /* Constraint.RelativeToParent는 Func<RelativeLayout, double> 타입의 델리게이트를 매개변수로 받음 */ layout.Children.Add(aquaBox, widthConstraint: Constraint.RelativeToParent(parent => parent.Width), heightConstraint: Constraint.RelativeToParent(parent => parent.Height * 0.3)); /* Constraint.RelativeToParent는 View와 Func<RelativeLayout, View, double> 타입의 델리게이트를 매개변수로 받음 * 여기서 View는 제약조건 설정을 위해 참고할 요소인 aquaBox */ layout.Children.Add(silverBox, xConstraint: Constraint.RelativeToView(aquaBox, (RelativeLayout, element) => element.Width * 0.1), yConstraint: Constraint.RelativeToView(aquaBox, (RelativeLayout, element) => element.Height - 20)); } } }