본문 바로가기
개발/안드로이드 어플

[Android] LayoutInflater 정보 (생성, 방법 비교, 구현)

by 외노자개발 2022. 12. 23.
반응형

 

 

 

안드로이드의 inflater란?


LayoutInflater는 지정된 xml 레이아웃(View) 리소스를 사용할 수 있는 메커니즘

 

 

 

 

View의 inflate에 대해 LayoutInflater에서 view를 생성하는 방법


자주 보는 방법
1. context#getSystemService(Context.LAYOUT_INFLATER_SERVICE);
2. Layoutinflater.from(Context context)
3. View.inflate(Context context, int resource, ViewGroup root)

//1 일반적인 생성 방법
LayoutInflater inflater = (LayoutInflater) context.SystemService(Context.LAYOUT_INFLATER_SERVICE);
//2 내용에는 1과 동일
LayoutInflater inflater = LayoutInflater.from(context);

//1,2로 LayoutInflater을 작성한 후 view를 작성
View view = inflater.inflate(R.layout.layout_sample, root);  

/* 3 
static으로View를inflate가능
편리하다 이것도 2를 콜 하고 1을 실행한다.
View의inflater메서드이기에 Layoutinflater클래스의inflater메서드와 인수가 다른 것을 주의
*/
View view = View.inflate(context, R.layout.layout_sample,root);

 

생성 방법별 비교


2,3을 이용해도,
아래 코드와 같이 최종적으로는 getSystemService( 생략)를 호출하고 있기 때문에 거의 동등
어느 것을 사용해도 거의 똑같이 사용할 수 있다.

 

/**
 * Obtains the LayoutInflater from the given context.
 */
public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater =
                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
    }

 

의문 1:inflater.inflate(int resource, ViewGroup root, boolean attachToRoot)의 제3 인수는?


LayoutInflater를 사용할 때 샘플 코드 등을 보고 attachToRoot라고 생각했기 때문에 조사

public View inflate (int resource, ViewGroup root, boolean attachToRoot)

어쨌든 attachToRoot에 true, false를 지정하면 view의 루트가 바뀔 것 같다
true : root로 지정한 것을 루트로 지정
false : root로 지정하지 않은 것은 루트로 지정하지 않다.

 

 

예) 다음과 같은 child.xml이 있는 경우

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     android:orientation="vertical"">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</LinearLayout>

 

 

//inflater작성作成
LayoutInflater inflater = LayoutInflater.from(this);
//적당한 레이아웃
FrameLayout root = new FrameLayout(this);  

//inflate
View view = inflater.inflate(R.layout.child, root, true or false);

즉,
true : 제일 부모의 레이아웃이 FrameLayout
false : 제일 부모의 레이아웃 LinearLayout
가 된다.
플러그 먼트로 inflate 하는 경우에 LayoutParams를 생각하고 조금 고려해 두는 것이 좋을 것 같다.

반응형

댓글