레이아웃 리소스는 Activity의 UI 또는 UI 구성요소의 아키텍처를 정의합니다.
- 파일 위치:
res/layout/filename.xml
파일 이름은 리소스 ID로 사용됩니다.- 컴파일된 리소스 데이터 유형:
View(또는 서브클래스) 리소스를 가리키는 리소스 포인터입니다.- 리소스 참조:
-
Java의 경우:
R.layout.filename
XML의 경우:@[package:]layout/filename - 문법:
-
<?xml version="1.0" encodin>g<="utf-8"? ViewGroup xmlns:android="http://schemas.android.com/apk/res/android" android:id="@[+][package:]id/resource_name" android:layout_height=["dimension" | "match_parent" | "wrap_content"] android:layout_width=["dimensi>on&qu<ot; | "match_parent" | "wrap_content"] [ViewGroup-specific attributes] View android:id="@[+][package:]id/resource_name" android:layout_height=["dimension" | "match_parent" >| "w<rap_content&q>uot;]< > a<ndroid:lay>out_width<=[&quo>t;dim<ension&quo>t; | <"match_parent" | "wrap_con>t<ent"]> [View-specific attributes] requestFocus/ /View ViewGroup View / /ViewGroup include layout="@layout/layout_resource"/ /ViewGroup
참고: 루트 요소는
ViewGroup,View또는<merge>요소가 될 수 있지만, 루트 요소는 하나만 있을 수 있으며 위와 같이android네임스페이스를 사용하는xmlns:android속성을 포함해야 합니다. - 요소:
-
android:id의 값
ID 값의 경우 일반적으로 다음 예와 같이
"@+id/name"문법 형식을 사용합니다. 더하기 기호(+)는 새 리소스 ID를 나타내며 리소스 정수가 아직 존재하지 않는다면aapt도구는R.java클래스에 새 리소스 정수를 만듭니다.<TextView android:id="@+id/nameTextbox"/>이제
nameTextbox이름은 이 요소에 연결된 리소스 ID입니다. 그런 다음 Java에서 ID에 연결된TextView를 참조할 수 있습니다.Kotlin
val textView: TextView? = findViewById(R.id.nameTextbox)
Java
TextView textView = findViewById(R.id.nameTextbox);
이 코드는
TextView객체를 반환합니다.하지만 이미 ID 리소스를 정의했고 아직 사용하지 않았다면
android:id값에서 더하기 기호를 제외하여View요소에 ID를 적용할 수 있습니다.android:layout_height 및 android:layout_width의 값
높이 및 너비 값은 Android에서 지원하는 모든 크기 단위(px, dp, sp, pt, in, mm) 또는 다음의 키워드를 사용하여 표현됩니다.
값 설명 match_parent상위 요소의 크기와 일치하도록 크기를 설정합니다. fill_parent를 지원 중단하기 위해 API 수준 8에 추가되었습니다.wrap_content이 요소의 콘텐츠에 맞도록 필요한 크기로만 크기를 설정합니다. 맞춤 뷰 요소
맞춤
View와ViewGroup요소를 만들 수 있고 요소를 표준 레이아웃 요소와 동일하게 레이아웃에 적용할 수 있습니다. 또한, XML 요소에서 지원되는 속성을 지정할 수도 있습니다. 자세한 내용은 맞춤 뷰 구성요소 만들기를 참고하세요. - 예:
res/layout/main_activity.xml에 저장된 XML 파일:<?xml version="1.0" encoding=<"utf-8"?> LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"<; android:orientation="vertical" > TextView android:id="@+id/text" android:layout_width="wrap_content" android:la<yout_height="wrap_content" android:text="Hello, I am a TextView" /> Button android:id="@+id/button" android:layout_wi<dth="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button" /> /LinearLayout>
다음 애플리케이션 코드는
onCreate()메서드에서Activity의 레이아웃을 로드합니다.-
Kotlin
public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) }
Java
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); }
- 참고 항목: