UI 레이아웃에서 퍼센트 값 주기
기존 안드로이드에서는 UI 레이아웃을 할 때, 퍼센트 값을 직접 사용할 수 없었다.(코드에서 직접 퍼센트 수치를 계산하는 것 제외) 그러나, Support Library 23버전에 추가된 PercentFrameLayout, PercentRelativeLayout을 사용하면, 퍼센트값을 이용해 레이아웃을 구성할 수 있다.
PercentFrameLayout, PercentRelativeLayout
각각 FrameLayout, RelativeLayout을 상속받았으므로 해당 레이아웃의 특성을 모두 가지고 있고, 추가적으로 자식 뷰들을 레이아웃 할 때 Percent 값을 지원한다.
사용할 수 있는 Percent 속성
Percent 수치를 사용할 수 있는 속성은 다음과 같다.
* layout_widthPercent
* layout_heightPercent
* layout_marginPercent
* layout_marginLeftPercent
* layout_marginTopPercent
* layout_marginRightPercent
* layout_marginBottomPercent
* layout_marginStartPercent
* layout_marginEndPercent
* layout_aspectRatio
- 각 속성의 이름을 보면 직관적으로 어떤 의미인지 알 수 있다.
- layout_widthPercent(heightPecent) 가 있으면 기존의 layout_width(height)를 생략해도 된다.
- 만약, 명시된 width/height의 퍼센트가 뷰의 내용보다도 작을 때, 리사이징 되도록 하고 싶다면, layout_width/height 속성을 wrap_content로 준다.
layout_aspectRatio는, 뷰의 width/height 비율을 지정하는 옵션이다.
android:layout_width="300dp"
app:layout_aspectRatio="250%" <!-- width의 250%만큼 height가 설정됨 -->
적용방법
Library 추가
app의 build.gradle에 다음의 dependancy를 추가한다.
dependencies {
...
compile "com.android.support:percent:25.2.0"
...
}
xml에서 사용
1.부모 레이아웃을 PercentFrameLayout, PercentRelativeLayout으로 추가한다.
2.http://schemas.android.com/apk/res-auto xml 네임스페이스를 추가한다.
3.자식 뷰에 필요한 속성을 추가한다.
<android.support.percent.PercentFrameLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
app:layout_widthPercent="50%"
app:layout_heightPercent="20%"
app:layout_marginTop="5%"
android:layout_gravity="left|center_vertical" />
<TextView
app:layout_widthPercent="20%"
app:layout_heightPercent="20%"
app:layout_marginTop="5%"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical" />
</android.support.percent.PercentFrameLayout>
코드에서 사용
1.Percent Layout의 자식뷰로부터 LayoutParams 객체를 얻는다.
2.getPercentLayoutInfo() 메서드를 호출하여 PercentLayoutInfo 객체를 얻는다.
3.얻은 PercentLayoutInfo 객체의 필드를 이용해 값을 적용한다.
PercentFrameLayout.LayoutParams params = (PercentFrameLayout.LayoutParams) mChild.getLayoutParams();
PercentLayoutHelper.PercentLayoutInfo layoutInfo = params.getPercentLayoutInfo();
layoutInfo.widthPercent = 0.20f;
mChild.setLayoutParams(params);