- Home ›
- Android入門 ›
- ImageButtonクラス ›
- HERE
表示するBitmapの指定
広告
ImageButtonに表示する画像を指定する方法を確認します。「ImageButton」クラスの親クラスである「ImageView」クラスで用意されている「setImageBitmap」メソッドを使います。
setImageBitmap public void setImageBitmap(Bitmap bm)
Parameters: bm 表示するBitmap
1番目の引数に表示するBitmapクラスのオブジェクトを指定します。(Bitmapクラスについては「Bitmapクラス」を参照して下さい)。
具体的には次のように記述します。
private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); Resources r = getResources(); Bitmap bmp = BitmapFactory.decodeResource(r, R.drawable.bitmapsample); ImageButton imgbutton = new ImageButton(this); imgbutton.setImageBitmap(bmp); setContentView(image, new LayoutParams(WC, WC)); }
サンプルプログラム
それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。
package jp.javadrive.android; import android.app.Activity; import android.os.Bundle; import android.widget.LinearLayout; import android.view.ViewGroup; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.widget.ImageButton; import android.content.Resources; public class Test02_01 extends Activity { private final int FP = ViewGroup.LayoutParams.FILL_PARENT; private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); LinearLayout linearLayout = new LinearLayout(this); linearLayout.setOrientation(LinearLayout.HORIZONTAL); setContentView(linearLayout); Resources r = getResources(); Bitmap bmp1 = BitmapFactory.decodeResource(r, R.drawable.star1); Bitmap bmp2 = BitmapFactory.decodeResource(r, R.drawable.star2); ImageButton imgbutton1 = new ImageButton(this); imgbutton1.setImageBitmap(bmp1); linearLayout.addView(imgbutton1, createParam(100, 100)); ImageButton imgbutton2 = new ImageButton(this); imgbutton2.setImageBitmap(bmp2); linearLayout.addView(imgbutton2, createParam(120, 80)); } private LinearLayout.LayoutParams createParam(int w, int h){ return new LinearLayout.LayoutParams(w, h); } }
また画像をリソースとしてプロジェクト内の「res/drawable」ディレクトリに配置しました。
ビルド後にエミュレーター上で実行します。
画像リソースからBitmapクラスのオブジェクトを作成し、Bitmapクラスのオブジェクトを使ってImageViewクラスのオブジェクトを作成しています。
( Written by Tatsuo Ikura )