Kotlinを使ってAndroidでURLからImageViewに画像を読み込む方法【初心者向け解説】
この記事では、Kotlinを使用してAndroidアプリでURLから画像をダウンロードし、ImageViewに表示する方法を段階的に解説します。ネットワーク上の画像を取得して画面に表示する、基本的な仕組みを学べる内容です。
手順1:新規プロジェクトの作成
まず、Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要な項目をすべて入力してプロジェクトを作成してください。
手順2:レイアウトファイル(activity_main.xml)の編集
次に、res/layout/activity_main.xmlに以下のコードを追加します。タイトル用のTextViewと、画像を表示するためのImageViewを配置しています。
<?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を継承した内部クラス「DownloadImageFromInternet」を作成し、doInBackground()内で指定したURLから画像をダウンロードし、onPostExecute()でImageViewにBitmapをセットしています。
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の編集
インターネット通信を行うため、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>
アプリの実行と動作確認
それでは、アプリを実行してみましょう。実機のAndroidスマートフォンをパソコンに接続していることを前提とします。Android Studioでプロジェクトのアクティビティファイルを開き、ツールバーにある実行アイコン
をクリックしてください。接続済みのモバイルデバイスを選択すると、実機の画面にアプリが起動します。
処理が完了すると、指定したURLの画像がImageViewに表示されます。


補足:AsyncTaskは非推奨(Deprecated)
なお、本記事で使用しているAsyncTaskは、現在Androidでは非推奨となっています。学習や検証には問題ありませんが、実際のアプリ開発では、CoilやGlideといった画像読み込みライブラリの利用が推奨されます。例えばCoilを使えば、以下のようにわずか1行で画像を読み込むことができます。
imageView.load("https://example.com/image.jpg")ライブラリを活用することで、キャッシュ管理やエラーハンドリングなども簡単に実装できるため、実運用ではぜひ検討してみてください。
-
AndroidでURLからImageViewに画像を読み込む方法を徹底解説
この記事では、AndroidアプリにおいてURLを指定してImageViewに画像を読み込む方法を、実際のサンプルコードとともにステップごとにわかりやすく解説します。ネットワーク上の画像を非同期でダウンロードして表示する基本的な仕組みを学びましょう。 手順1:Android Studioで新規プロジェクトを作成する まず、Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成してください。 手順2:res/layout/activity_main.xml にコードを追加する 次に、レイアウトフ
-
AndroidアプリのImageViewで画像を読み込んで表示する方法を徹底解説
この記事では、AndroidアプリにおいてImageViewを使って画像を読み込み、画面に表示する方法をステップごとに解説します。ボタンをタップすると表示中の画像が切り替わるシンプルなサンプルアプリを題材にしているので、ImageViewの基本的な使い方を学びたい初心者の方にもおすすめです。 手順1:Android Studioで新規プロジェクトを作成する まずはAndroid Studioを起動し、メニューから「File」→「New Project」を選択して新しいプロジェクトを作成します。プロジェクト名やパッケージ名など必要な項目を入力して、セットアップを完了させてください。 手順2:レイ