Java (Android): 画像を画面に表示

device-2013-01-02-231054

package jp.feb19.snippets;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class ImageViewActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);
		
		// Bitmap クラスを使う
		Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample);
		ImageView image = new ImageView(this);
		image.setImageBitmap(bitmap);
		layout.addView(image, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
		// setImageResource メソッドを使う
		ImageView image2 = new ImageView(this);
		image2.setImageResource(R.drawable.sample);
		layout.addView(image2, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
		setContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
	}
}