Android 프로그래밍 2

본문 바로가기
사이트 내 전체검색


Android 프로그래밍 2
Android 프로그래밍 2

6. LayoutInflater 실습

페이지 정보

작성자 관리자 댓글 0건 조회 1,992회 작성일 20-07-01 15:29

본문

6. LayoutInflater 실습

layout을 생성하는 것을 inflate한다고 한다.

View를 정의한 XML이나 java/Kotlin 파일대로 View를 inflate한다고 생각하면 될 것이다.


inflate는 getLayoutInflater()를 이용하여 현재 context와 폰 화면에 맞는 LayoutInflater객체를 생성해서 사용해야 한다.


아래와 같이 layoutInflater객체를 얻어온다.


1. 새프로젝트 생성


프로젝트명 : inflateTest1



2. inflate할 ViewXML 생성


파일명 : layout_imageview.xml


<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/image_to_attach"
android:src="@mipmap/ic_launcher"/>


3. activity_main.xml 수정


이미지뷰을 붙일 곳의 ViewGroup에 id를 붙여준다.

여기서는 LinearLayout를 ViewGroup으로 사용한다.


<?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"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linear_root"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>


4. MainActivity.kt 수정


실제로 inflate() 메소드를 사용한다.


package kr.co.leelab.inflatetest1

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.LinearLayout

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val mInflater: LayoutInflater = this.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val mRootLinear : LinearLayout = findViewById(R.id.linear_root) as LinearLayout
mInflater.inflate(R.layout.layout_imageview, mRootLinear, true)

}
}




5. 실행


아래와 같이 이미지뷰가 HelloWorld 밑의 LinearLayout에 붙어서 잘 나타난다.



1.PNG

댓글목록

등록된 댓글이 없습니다.


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.