Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android 앱에서 ImageView로 이미지를 로드하고 표시하는 방법

개요

이 튜토리얼에서는 Android 앱에서 ImageView 위젯을 활용해 이미지를 로드하고 화면에 표시하는 방법을 단계별로 살펴봅니다. 나아가 버튼을 클릭하면 이미지가 다른 리소스로 교체되는 간단한 예제까지 함께 구현해 보겠습니다.

1단계: 새 프로젝트 만들기

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하여 새 프로젝트를 생성합니다. 프로젝트 이름, 패키지명, 최소 SDK 버전 등 필요한 모든 정보를 입력해 초기 설정을 완료하세요.

2단계: 레이아웃 파일 작성 (res/layout/activity_main.xml)

화면 구성을 위해 LinearLayout 안에 ImageView와 Button을 배치합니다. 아래 코드를 activity_main.xml 파일에 추가하세요.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".MyAndroidAppActivity">

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<Button
android:id="@+id/btnChangeImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Image"/>

</LinearLayout>

ImageView는 이미지가 표시될 영역을 담당하고, 'Change Image'라는 문구를 가진 Button은 클릭 시 이미지를 교체하는 역할을 합니다.

3단계: 액티비티 코드 작성 (MyAndroidAppActivity.java)

버튼 클릭 이벤트를 처리하고 ImageView에 새 이미지를 적용하는 자바 코드입니다. 아래 내용을 액티비티 소스 파일에 추가하세요.

package com.example.sample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MyAndroidAppActivity extends AppCompatActivity {

Button button;
ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}

public void addListenerOnButton() {
image = (ImageView) findViewById(R.id.imageView1);
button = (Button) findViewById(R.id.btnChangeImage);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
image.setImageResource(R.drawable.ic_launcher_background);
}
});
}
}

코드의 핵심은 setOnClickListener()로 버튼 클릭 리스너를 등록하고, onClick() 콜백 안에서 setImageResource() 메서드를 호출해 drawable 리소스를 ImageView에 적용하는 부분입니다. 버튼이 눌릴 때마다 해당 이미지로 화면이 갱신됩니다.

4단계: 매니페스트 설정 (AndroidManifest.xml)

액티비티를 앱의 시작점(Launcher Activity)으로 등록하기 위해 아래 코드를 AndroidManifest.xml에 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.sample">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<activity android:name=".MyAndroidAppActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

</application>
</manifest>

5단계: 애플리케이션 실행

이제 앱을 실행해 결과를 확인해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하세요. 기기 선택 창에서 본인의 모바일 기기를 고르면, 기기 화면에 아래와 같은 기본 화면이 나타납니다. 'Change Image' 버튼을 누르면 ImageView에 표시된 이미지가 즉시 변경되는 것을 확인할 수 있습니다.

Android 앱에서 ImageView로 이미지를 로드하고 표시하는 방법

참고 사항

예제 코드의 android.support.v7.app.AppCompatActivity는 구버전 지원 라이브러리 클래스입니다. 최신 Android Studio 프로젝트는 AndroidX를 기본으로 사용하므로, import 문을 androidx.appcompat.app.AppCompatActivity로 변경하면 됩니다. 또한 R.drawable.ic_launcher_background 대신 res/drawable 폴더에 넣어 둔 원하는 이미지 리소스를 지정하면 자유롭게 응용할 수 있습니다.