Android 사용 하다 보면 xml로 된 layout 파일을 어떤 식이든지 View 형태의 객체로 얻고 싶은 경우가 있을 것 이다. (없으면 말고...)

이 때 사용되는 녀석이 LayoutInflater 라는 녀석인데.
첨음 내가 이걸 접할때 대체 뭐하는 넘이지 하는 막연한 생각만 가지고 있어서 설명을 해볼까 함.

우선 layout.xml이 필요함.
그리고 LayoutInflater가 필요한데.
얻는 방법은 2가지가 있음.
- LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- LayoutInflater inflater2 = getLayoutInflater();

각각 차이점은 inflater는 system에서 얻어 오는 방법이고,
inflater2는 Activity에서 제공하는 메소드를 이용해 얻어 오는 방법임. (둘다 별반 차이없음)

inflater는 View객체를 반환 해주는 4가지 메소드가 존재함.
// 리소스(R.layout.xxx), root
inflater.inflate(resource, root);
// XMLparser, root  
inflater.inflate(parser, root);
// 리소스(R.layout.xxx), root, attach 조건(보통 false)
inflater.inflate(resource, root, attachToRoot);
//  XMLparser, root, attach 조건(보통 false)
inflater.inflate(parser, root, attachToRoot);
이렇게 4가지 이고 각각의 파라메터에 대한 부연 설명을 하자면,
리소스는 프로젝트/res/layout 폴더에 들어 있는 xml 파일을 지정 하면됨,
XMLparser는 잘 안쓰니 버리고(나도 써본적이 없음),
root는 내가 지정한 리소스(xml 파일)이 어디에 붙을 껀지 지정하는 것임(없으면 null 넣으면됨),
attach 조건 이게 좀 복잡한데 이해 하려면  LayoutParams 이란 걸 알아야함.
LayoutParams은 xml 상에서 (android:layout_width, android:layout_height) 을 code로 정의 해주는 녀석인데 이녀석에 대한 생성 기준을 어디로 설정 할 것이냐 묻는 것이다.

예를 들어 내가 show_item.xml 파일을 list라는 LinearLayout 에다가 add 하고 싶다고 한다면.
//  LinearLayout 객체 생성
LinearLayout list = (LinearLayout)findViewById(R.id.list);
//  LinearLayout 객체 초기화 
list.removeAllViews();
//  LayoutInflater 객체 생성
LayoutInflater inflater = getLayoutInflater();
//  View 객체 생성
View view =inflater.inflater(R.layout.show_item, list(View를 붙일 녀석), false(붙일 조건));
//  LinearLayout 객체에 View 객체 추가 
list.add(view);
이렇게 될 것이다. 이때 붙일 조건이 중요한데 이녀석이 false 이면, show_item.xml에서 사용된 (android:layout_width, android:layout_height) 값들을 list에다가 새로 추가를 해주는 작업을 하게 된다. (맞니?...)
Android Developer에 있는 붙일 조건에 대한 설명
(Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML)

이렇덴다.. 후후. 
 

+ Recent posts