Android LayoutInflater
LayoutInflater 란?
- 안드로이드에서 View를 만드는 방법 중 하나
- xml에 정의된 Resource 를 View 객체로 반환해 주는 역할을 한다.
- xml 에 미리 정해둔 틀을 실제 메모리에 올려주는 역할을 한다.
- Inflate는 부풀리다라는 뜻으로 만들어둔 반죽을 빵처럼 부풀려 실제 식탁에 올려주는 역할로 묘사할 수 있다.
- Activity 를 만들면 onCreate 에 추가되는 setContentView 메서드와 유사한 역할
- xml 레이아웃 파일에 대한 뷰를 생성할 때 LayoutInflater 를 이용해야 한다.
- LayoutInflater 객체의 inflate 메서드를 이용해 새로운 뷰를 생성할 수 있다.
- inflate(xml파일, 만든 뷰를 넣을 부모 layout/container, 바로 inflate 할지의 여부)
- root를 지정하지 않을 경우, xml 상의 최상위 뷰의 xml layout 설정들은 무시된다.
LayoutInflater 생성하는 3가지 방법
- val inflater : LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
- context 에서 LayoutInflater 를 가져온다.
- val inflater : LayoutInflater = getLayoutInflater()
- activity 에서 LayoutInflater 를 얻어온다. (Activity 는 자신의 window의 LayoutInflater 를 사용)
- val inflater : LayoutInflater = LayoutInflater.from(context)
- LayoutInflater 에 static 으로 정의되어있는 LayoutInflater.from()을 이용해 LayoutInflater 를 만든다.
- 내부적으로 context에서 LayoutInflater 를 가져온다. (1번 처럼)
LayoutInflater 사용 시 주의사항
- inflate() 메서드로 layout을 inflate 한 경우, 해당 xml의 land, port layout을 자동으로 참조하게 된다.
- inflate() 된 view 의 child view는 inflate 된 view.findViewById로 찾아야 한다.
- inflate() 된 view의 layoutParams 속성은 실제 layout 에서 match_parent 라도, wrap_content 로 강제로 변경된다. (inflate 된 view는 parent 가 없어지기 때문에 강제로 wrap_content 시킨다.)
- inflate 된 뷰에서 다시 layout inflater 를 사용할 경우, 기존의 findViewById와 event 설정들이 모두 사라진다.
참고 링크
'안드로이드 > 정리(Android)' 카테고리의 다른 글
(Android) Glide란 무엇인가? (0) | 2022.02.03 |
---|---|
(Android) RecyclerView의 성능 개선 정리 (0) | 2022.01.26 |
(Android) Handler란 무엇일까? (0) | 2022.01.13 |
(코틀린 kotlin) Mutable과 Imutable 유형 정리 (0) | 2021.12.24 |
(Android) 개발 필수 스택 (0) | 2021.12.18 |