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

코틀린(Kotlin)으로 안드로이드 ImageView에 URL 이미지 로드하는 방법

코틀린으로 안드로이드 ImageView에 URL 이미지 로드하기

이 튜토리얼에서는 코틀린(Kotlin)을 사용해 안드로이드 앱에서 URL을 통해 ImageView에 이미지를 불러오는 방법을 단계별로 살펴봅니다. 웹상의 이미지를 다운로드해 화면에 표시하려면 네트워크 작업을 메인 스레드가 아닌 백그라운드에서 처리해야 하는데, 여기서는 AsyncTask를 활용한 기본적인 방식을 다룹니다.

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

Android Studio에서 File ⇒ New Project 메뉴로 이동한 뒤, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력해 새 프로젝트를 만듭니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="Load Image From URL in Android ImageView"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="24sp"
        android:textStyle="bold" />
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/text"
        android:layout_marginTop="5dp" />
</RelativeLayout>

3단계: MainActivity.kt 작성

src/MainActivity.kt 파일에 아래 코드를 추가합니다. AsyncTask의 doInBackground()에서 이미지를 다운로드하고, onPostExecute()에서 완성된 비트맵을 ImageView에 설정하는 구조입니다.

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.AsyncTask
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        DownloadImageFromInternet(findViewById(R.id.imageView))
            .execute("https://images.unsplash.com/photo-1535332371349-a5d229f49cb5?ixlib=rb-1.2.1&w=1000&q=80")
    }

    @SuppressLint("StaticFieldLeak")
    @Suppress("DEPRECATION")
    private inner class DownloadImageFromInternet(var imageView: ImageView) : AsyncTask<String, Void, Bitmap?>() {
        init {
            Toast.makeText(applicationContext, "Please wait, it may take a few minute...", Toast.LENGTH_SHORT).show()
        }
        override fun doInBackground(vararg urls: String): Bitmap? {
            val imageURL = urls[0]
            var image: Bitmap? = null
            try {
                val `in` = java.net.URL(imageURL).openStream()
                image = BitmapFactory.decodeStream(`in`)
            } catch (e: Exception) {
                Log.e("Error Message", e.message.toString())
                e.printStackTrace()
            }
            return image
        }
        override fun onPostExecute(result: Bitmap?) {
            imageView.setImageBitmap(result)
        }
    }
}

4단계: 매니페스트에 인터넷 권한 추가

androidManifest.xml 파일에 아래 코드를 추가합니다. 외부 URL에서 이미지를 내려받으려면 android.permission.INTERNET 권한 선언이 반드시 필요합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
    <uses-permission android:name="android.permission.INTERNET"/>
    <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=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘(녹색 재생 버튼)코틀린(Kotlin)으로 안드로이드 ImageView에 URL 이미지 로드하는 방법을 클릭하세요. 실행 옵션 목록에서 본인의 모바일 기기를 선택하면 기기에 앱이 설치·실행되고, 지정한 URL의 이미지가 ImageView에 표시됩니다.

코틀린(Kotlin)으로 안드로이드 ImageView에 URL 이미지 로드하는 방법

코틀린(Kotlin)으로 안드로이드 ImageView에 URL 이미지 로드하는 방법

참고: 실무에서 권장되는 대안

AsyncTask는 현재 구식(Deprecated) API이므로 실제 배포용 앱에서는 Glide나 Coil 같은 이미지 로딩 라이브러리를 사용하는 것이 좋습니다. 이들 라이브러리는 캐싱, 오류 처리, 생명주기 대응 등을 자동으로 처리해 주기 때문에 더 간결하고 안정적인 코드를 작성할 수 있습니다. 예를 들어 Coil을 사용하면 아래 한 줄로 동일한 기능을 구현할 수 있습니다.

imageView.load("https://images.unsplash.com/photo-1535332371349-a5d229f49cb5")