2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Android/Java】srcとbackgroundの違い

Last updated at Posted at 2021-04-25

ImageViewやImageButtonで画像リソースを設定するときに用いる

基本的にはbackgroundでリソースを指定していたが、他人の実装ソースではsrcを使用していたので把握している限りの違いを確認する。

Stack Overflowで同じ質問がヒットしたのだがそこから抜粋すると

background指定

  • リソースのオリジナルサイズ関係なしに指定したwidthとheightに調整される
<ImageButton
    android:id="@+id/button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:background="@drawable/resource_button"/>

スクリーンショット 2021-04-25 16.40.40.png

※実際の細かい調整は省略

src指定

  • リソースのオリジナルサイズで表示される
<ImageButton
    android:id="@+id/button"
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:src="@drawable/resource_button"
    android:background="#00000000"/>

スクリーンショット 2021-04-25 16.41.42.png

※実際の細かい調整は省略

この場合だと、縦横は60dpで指定しているもののリソースサイズはそれより大きいため途中で切られてしまう。もしbackgroundの時のようにサイズ調整したい場合はandroid:scaleType="fitCenter"を指定するとOK

Stack Overflowに戻るが

The src to an ImageView has additional features:

  • different scaling types
  • adjustViewBounds for setting bounds to match image dimensions
  • some transformations such as alpha-setting

とあるように、srcの方が様々な設定ができる様子。

またbackgroundは動的に変えることができ、Javaだと

private ImageView view;
/*
 *  中略
 */

view.setBackgroundResource(R.drawable.resource_button); //画像リソースを指定する場合

Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.btn, null);
view.setBackground(drawable);     //drawableファイルを設定する場合

view.setBackground(null);   //リソースをクリアする場合

と変えられるが、レイアウトファイルでsrc指定すると上の処理を実行しても反映されない。background指定内容の前面にsrc指定内容が表示されている様子。

以下はbackgroundを黒色指定して、srcにリソースを指定した場合。

<ImageView
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:src="@drawable/ic_launcher_foreground"
    android:background="@color/black"/>

スクリーンショット 2021-04-25 18.12.31.png

結論

  • オリジナルリソースの縦横の比率を維持したいならsrc指定がベスト
  • 動的に変えたいならbackground指定(src指定したリソースを動的に変える方法があるのか不明)

試した環境

  • Android Studio4.1.2
  • Android10
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?