ImageButtonに画像を設定するには、Androidではどのようにすればよいですか?
AndroidでImageButtonに画像を設定するには、次の手順に従ってください。
- XMLレイアウトファイルで、ImageButtonをレイアウトに追加します。例:
<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_image" />
@drawable/my_imageは、設定したい画像リソースを表します。res/drawableディレクトリに画像リソースファイルを格納できます。
- Javaコードで、ImageButton のインスタンスを取得し、画像リソースを設定する方法を見てみましょう。
ImageButton imageButton = findViewById(R.id.imageButton);
imageButton.setImageResource(R.drawable.my_image);
R.drawable.my_imageは設定するイメージリソースで、setImageResource()メソッドでイメージを設定できます。
ImageButtonのさまざまな状態(押し下げ、無効など)に異なる画像を設定するには、android:background属性を使用してバックグラウンドリソースを設定し、JavaコードでsetBackgroundResource()メソッドを使用して各状態のバックグラウンドリソースを設定できます。