이 글에서는 안드로이드에서 Picasso 라이브러리와 코틀린(Kotlin)을 사용해 인터넷상의 이미지를 다운로드하고 화면에 표시하는 방법을 단계별로 살펴봅니다.
1단계: 새 프로젝트 생성 및 의존성 추가
안드로이드 스튜디오에서 File → New Project를 선택해 새 프로젝트를 생성하고, 필요한 정보를 모두 입력합니다.
그다음 build.gradle(Module: app) 파일에 아래 의존성을 추가합니다.
implementation 'com.squareup.picasso:picasso:2.4.0'
의존성을 추가한 후에는 반드시 Sync Now를 클릭해 Gradle을 동기화해야 합니다.
2단계: 레이아웃 작성 (activity_main.xml)
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 이미지를 표시할 ImageView와 다운로드를 실행할 Button으로 구성되어 있습니다.
<?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:paddingBottom="4dp"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/btnDownload" />
<Button
android:id="@+id/btnDownload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Download Image"
android:textAlignment="center" />
</RelativeLayout>3단계: 메인 액티비티 코드 작성 (MainActivity.kt)
src/MainActivity.kt 파일에 아래 코드를 작성합니다. 버튼을 클릭하면 Picasso가 지정된 URL의 이미지를 로드해 ImageView에 표시합니다.
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.squareup.picasso.Picasso
class MainActivity : AppCompatActivity() {
lateinit var imageView: ImageView
lateinit var btnDownload: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
imageView = findViewById(R.id.imageView)
btnDownload = findViewById(R.id.btnDownload)
btnDownload.setOnClickListener {
Picasso.with(this)
.load("https://images.unsplash.com/photo-1555083892-97490c72c90c?ixlib=rb-1.2.1&w=1000&q=80")
.into(imageView);
}
}
}4단계: 인터넷 권한 설정 (AndroidManifest.xml)
네트워크에서 이미지를 불러오려면 인터넷 권한이 필요합니다. androidManifest.xml 파일에 아래와 같이 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>앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. 안드로이드 스튜디오에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 Run(실행) 아이콘
을 클릭하세요.
실행 옵션에서 자신의 모바일 기기를 선택하면, 기기 화면에 기본 화면이 표시됩니다. 이후 Download Image 버튼을 누르면 Picasso가 이미지를 다운로드해 화면에 나타냅니다.
