Androidアプリ内にて画像表示(埋め込む)する方法を紹介します。2つともとても簡単な方法なので好きな方を活用ください。サンプルはKotlinで作成してます。
画像表示するための前準備・手順
アプリ内に画像を表示するために、以下手順を行います。
- 画像ファイルを用意(ファイル名はすべて小文字推奨)
- 画像ファイルをプロジェクト内へコピー(AndroidStudio上にて「drawable」ファルダヘドラッグアンドドロップする)
- xml/kotlinから画像ファイルを読み込み、ImageViewに表示させる。
2の画像ファイルを配置する場所は以下の通り。

サンプルコード
画像(sampleimage.jpg)を表示するサンプルを作成しました。
アプリを実行した時点で画像は両方とも表示されます(下画像)。
方法①:xmlから画像ファイル読み取り
方法②:Kotlinから画像ファイル読み取り(binding活用)

2つの方法を1つのサンプルコードにまとめています。混同するほどではないですがその点は意識して見てください。
UIとKotlinの紐づけはbindingを活用しています(bindingの仕方はこちら)。
xmlは以下の通り。
adjustViewBoundsをtrueにすると画像の縦横比を維持して表示されます。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- 方法①:xmlで直接読み取る -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff0"
android:text="★xmlから直接読み込む" />
<ImageView
android:src="@drawable/sampleimage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:adjustViewBounds="true"
/>
<Space
android:layout_width="match_parent"
android:layout_height="30dp" />
<!-- 方法②:Kotlinからbindingで表示 -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FF0"
android:text="★bindingを用いてKotlin側から読み込む" />
<ImageView
android:id="@+id/tvSampleImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:adjustViewBounds="true"
/>
</LinearLayout>
Kotlinは以下の通り。
class MainActivity : AppCompatActivity() {
private lateinit var binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Binding関連
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
// 方法②:画像表示
binding.tvSampleImage.setImageResource(R.drawable.sampleimage)
}
}
さいごに
どちらの方法でもよいですが、動的に画像を差し替える場合などは方法②を使うことになると思うので私はそちらをメインに使用しようと思います。
ギャラリーからの画像を取得・表示する方法は以下記事を参考ください。



コメント