728x90

Android Studio 에서 xml 파일을 추가하는 방법

오랫만에 접속하면 이런 방법마저 잊어버리게 되더라. 그래서 적어둔다.




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

<ImageButton
android:id="@+id/ib01"
android:src="@android:drawable/sym_def_app_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<EditText
android:id="@+id/et01"
android:hint="예상 우승 후보팀을 입력하세요"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

이 XML 파일을 View 객체로 만들기 위해서는 LayoutInflator를 이용해야 한다.

안드로이드에서 inflate 를 사용하면 xml 에 씌여져 있는 view 의 정의를 실제 view 객체로 만드는 역할을 한다.

자바 프로그램 코드상에서는 레이아웃 인플레이터에 직접 접근하지 못하고

getLayoutInflater() 메소드를 이용하거나, getSystemService(String) 메소드를 호출해 반환값으로 LayoutInflater 객체를 받아야 한다.

사용자의 화면에 보여지는 것들은 Activity 위에 있는 View다.


Layout Inflater
- 레이아웃 인플레이터는 레이아웃 xml 파일에 상응하는 뷰 객체를 반환받는 데 사용한다
- 자바 프로그램 코드상에서는 레이아웃 인플레이터에 직접 접근하지 못하고 getLayoutInflater() 메소드를 이용하거나
getSystemService(String) 메소드를 호출해 반환값으로 LayoutInflater 객체를 받아야 한다.
- 보통 자바 코드에서 View, ViewGroup 을 사용하거나, Adapter의 getview() 또는 Dialog, Popup 구현시
배경화면이 될 Layout을 만들어 놓고 View의 형태로 반환 받아 Acitivity에서 실행 하게 된다.


inflate(int resource, ViewGroup root, boolean attachToRoot)
- 레이아웃 XML파일을 View객체로 만들기 위해서는 LayoutInflater내의 inflater 메서드를 사용
- resource: view를 만들고 싶은 레이아웃 파일의 id (
inflate할 대상의 xml 리소스)

ex) R.layout.custom

- 두 번째 인수는 생성된 뷰의 루트로 사용할 뷰 객체. 리소스 내에 루트가 따로 있다면 null.


inflate 를 사용하기 위해서는 우선 inflater 를 얻어와야 한다.
LayoutInflater inflater = (LayoutInflater) getSystemService( Context.LAYOUT_INFLATER_SERVICE );
LinearLayout linearLayout = (LinearLayout) inflater.inflate( R.layout.custom, null);
setContentView( linearLayout ); // 가져온 View 를 화면에 그린다.


/* We get the inflator in the constructor */
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

--> getSystemService(Context.LAYOUT_INFLATER_SERVICE) = LayoutInflater 객체를 반환받는다.


// 인플레이트를 얻어오는 다른 방법
LinearLayout linearLayout = (LinearLayout) View.inflate(MainActivity.this, R.layout.custom, null);
// Inflate된 View에서 Child인 EditText를 얻어 오기
EditText editText = (EditText) linearLayout.findViewById(R.id.et01);




블로그 이미지

Link2Me

,