반응형

LayoutInflater이란?

 

LayoutInflater은 XML에 미리 정의해둔 틀을 실제 메모리에 올려주는 역할을 한다.

Inflater 단어의 뜻이 부풀리다라는 의미로써 LayoutInflater라는 단어에서도 유추가 가능하다.

 

즉, LayoutInflater는 XML에 정의된 Resource를 View 객체로 반환해주는 역할을 한다.

우리가 매번 사용하는 onCreate() 메서드에 있는 setContentView(R.layout.activity_main) 또한 Inflater 역할을 한다.

(이 함수의 내부에서 layout inflater가 실행되어 view들을 객체화한다.)

 

www.edwith.org

 

 

LayoutInflater 생성 방법

 

getSystemService

 

LayoutInflater 객체는 시스템 서비스 객체로 제공되기 때문에 getSystemService 메소드를 이용해 참조할 수 있다.

getSystemService(Context.LAYOUT_INFLATER_SERVICE)

그리고 뷰 객체가 있으면 그 뷰 객체에 인플레이션한 결과물을 설정하게 된다.

예를들어 FrameLayout 객체이거나 FrameLayout을 상속한 뷰 객체가 container라는 이름으로 만들어져 있다면

아래와 같은 코드를 이용해 레이아웃 인플레이션을 진행할 수 있다.

 

FrameLayout container = (FrameLayout) findViewById(R.id.container);

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
inflater.inflate(R.layout.sub1, container, true);

 

즉, LayoutInflater을 사용하기 위한 조건은 다음과 같다.

 

1. 객체화하고자 하는 xml파일(sub1.xml)을 작성한다.

 

2. LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

라는 코드를 사용해서 LayoutInflater 객체 사용할 준비를 완료한다.

 

3. inflater.inflate(R.layout.sub1, container, true);

라는 코드를 통해서 사전에 미리 선언해뒀던 container라는 레이아웃에 작성했던 xml의 메모리객체가 삽입되게 된다.

매개변수 설명 : inflate( 1.객체화하고픈 xml파일, 2.객체화한 뷰를 넣을 부모 레이아웃/컨테이너, 3.true(바로 인플레이션 하고자 하는지))

반응형