Android 프로그래밍 2

본문 바로가기
사이트 내 전체검색


Android 프로그래밍 2
Android 프로그래밍 2

5. Inflate 기초

페이지 정보

작성자 관리자 댓글 0건 조회 2,075회 작성일 20-07-01 14:17

본문

5. Inflate 기초

Inflate 는 사전적 의미로 "부풀리다" 라는 뜻입니다.
안드로이드에서 inflate 를 사용하면 xml 에 씌여져 있는 view 의 정의를 실제 view 객체로 만드는 역할을 합니다.


가장 자주 쓰이는 inflater 는 LayoutInflater 이며 MenuInflater 도 있습니다.


LayoutInflater는 안드로이드에서 View를 만드는 가장 기본적인 방법입니다.


Fragment의 View를 만들거나 RecyclerView에서 ViewHolder를 만들때, CustomView에서 xml로 정의된 View를 merge할 때 등 여러곳에서 사용됩니다.


LayoutInflater 생성하기


가장 기본적인 방법으로 context에서 LayoutInflater를 가져오는 방법입니다.


val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)


Activity에서는 LayoutInflater를 쉽게 얻어올수 있도록 getLayoutInflater() 를 제공합니다.
Activity는 자신 window의 LayoutInflater를 사용합니다.


val inflater: LayoutInflater = getLayoutInflater()


LayoutInflater.from()는 가장 자주 사용하는 방법으로, LayoutInflater에 static으로 정의되어있는 LayoutInflater.from을 통해 LayoutInflater를 만드는 방법입니다. 

내부적으로 context#getSystemService를 호출 하고 있으며, 같은 context에서는 같은 객체를 리턴하기 때문에 굳이 멤버 변수로 선언해 놓지 않고 필요할 때마다 호출해서 사용해도 괜찮습니다.


val inflater: LayoutInflater = LayoutInflater.from(context)



AsyncLayoutInflater

 

LayoutInflate는 동기적으로(synchronous) 뷰를 생성 하기 때문에, support package에서는 비동기적으로 뷰를 만들 수 있는 AsyncLayoutInflater를 제공합니다.
XML내의 뷰 hierarchy가 복잡하거나 UI스레드에서 inflate하는데 시간이 너무 오래걸린다면 사용 할 수 있습니다.


val inflater = AsyncLayoutInflater(context)
inflater.inflate(R.layout.my_layout, parent) { view, resId, parent ->
  // parent.addView(view)
}


간단하게 비동기로 뷰를 생성 할수 있지만. 몇가지 주의할 점이 있습니다
1. parent의 generateLayoutParam()이 thread safe해야 합니다
2. 생성자에서 Handler를 만들거나 Looper.myLooper()를 사용하면 안됩니다.
3. LayoutInflater.Factory를 사용 할 수 없습니다.
4. Fragment를 inflate 할 수 없습니다.


View inflate하기

 

inflater에서 View객체를 만들기 위해서는 inflater를 사용 하면 됩니다.

inflate(resource: Int, root: ViewGroup?, attachToRoot: Boolean)

resource: View를 만들고 싶은 레이아웃 파일의 id입니다. R.layout.my_view
root: 생성될 View의 parent를 명시해줍니다. null일 경우에는 LayoutParams값을 설정 할 수 없기 때문에 XML내의 최상위 android:layout_xxxxx값들이 무시되고 merge tag를 사용 할 수 없습니다.
attachToRoot: true 로 설정해 줄 경우 root의 자식 View로 자동으로 추가됩니다. 이때 root는 null 일 수 없습니다.
return: attachToRoot에 따라서 리턴값이 달라집니다. true일 경우 root가, false일 경우 XML내 최상위 뷰가 리턴됩니다.



View.inflate()

 

View에서는 LayoutInflater의 inflate까지 한번에 실행하는 View.inflate()를 제공 하고 있습니다.
(내부에서는 LayoutInflater.inflate를 수행함) 이 때 주의할점은 parent가 null이 아니면 자동으로 attach됩니다.


View.inflate(context, R.layout.my_layout, parent)



댓글목록

등록된 댓글이 없습니다.


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.