프로그래밍/안드로이드

안드로이드 - LayoutInflater를 활용한 레이아웃 겹치기

가카리 2015. 8. 30. 17:47
반응형

 

윈도우는 빈 채로 생성되며 빈 윈도우 안에 레이아웃을 채워 넣어 UI를 구성하는데 이때는 다음 메소드를 호출 한다.

 

void setContentView(int layoutResID)

void setContentView(View view, [ViewGroup.LayoutParams params])

void addContentView(View view, ViewGroup.LayoutParams params)

 

다음 예제는 2개의 xml파일을 겹쳐서 보여주는 예제이다.

 

overlay1.xml

 

<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="바닥 레이아웃" />

    <Button

     android:layout_width="wrap_content"

     android:layout_height="wrap_content"

     android:text="바닥의 버튼"

     />

 

</LinearLayout>

 

overlay2.xml

 

<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:gravity="center"

    android:background="#40ffff00"

>

    <TextView

     android:layout_width="wrap_content"

     android:layout_height="wrap_content"

     android:text="이것은 위쪽의 레이아웃 입니다."/>

 

    <Button

     android:layout_width="wrap_content"

     android:layout_height="wrap_content"

     android:text="위쪽 버튼"/>

 

</LinearLayout>

 

Overlay.java

 

package com.example.overlay;

 

import android.app.Activity;

import android.content.Context;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.Window;

import android.widget.LinearLayout;

 

public class Overlay extends Activity {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        Window win = getWindow();

        win.setContentView(R.layout.overlay1);

        

        //전개자로 xml파일을 가져옴

        LayoutInflater inflater = (LayoutInflater)getSystemService(

                Context.LAYOUT_INFLATER_SERVICE);

        LinearLayout linear = (LinearLayout)inflater.inflate(R.layout.overlay2, null);

          

        //파라미터를 세팅해줌

        LinearLayout.LayoutParams paramlinear = new LinearLayout.LayoutParams(

                LinearLayout.LayoutParams.MATCH_PARENT,

                LinearLayout.LayoutParams.MATCH_PARENT

                );

        

        //윈도우에 추가시킴

        win.addContentView(linear, paramlinear);

        

        

    }

 

 

}

 

실행화면

 

아래쪽 레이아웃은 위쪽 레이아웃 때문에 색상이 약간 변한다. 하지만 두 버튼은 독립적으로 동작해서 클릭 리스너를 추가 시킬 수 있다.

 

 

 

 

반응형