C/C++プログラマの管理者が, Androidプログラムにチャレンジ. AndroidプログラミングのTipsをメモっていく予定です.

イメージを表示するには, イメージビュー(ImageView)クラスを使う.

イメージの表示

  • res/drawable-hdpi/photo.jpg
    • 画像を準備する.

(出典 http://sports.livedoor.com/ )
  • res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  >
  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/msg1_label"
    />
  <ImageView android:id="@+id/imgview1_id"
    android:layout_width="wrap_content"
    android:layout_height="100dip"
    />
  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/msg2_label"
    />
  <ImageView android:id="@+id/imgview2_id"
    android:layout_width="wrap_content"
    android:layout_height="100dip"
    />
  <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/msg3_label"
    />
  <ImageView android:id="@+id/imgview3_id"
    android:layout_width="wrap_content"
    android:layout_height="100dip"
    />
</LinearLayout>
  • ImageViewActivity.java
    • findViewByIdメソッドで, 指定したリソースインデックスのIDに対応したImageViewのインスタンスを取得する.
    • ImageView#setImageResource, setImageBitmap, setImageDrawableメソッドで, 画像を設定する.
package com.moonlight_aska.android.imageview;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class ImageViewActivity extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Resourceを設定
    ImageView imgView1 = (ImageView)findViewById(R.id.imgview1_id);
    imgView1.setImageResource(R.drawable.photo);
    // Bitmapを設定
    ImageView imgView2 = (ImageView)findViewById(R.id.imgview2_id);
    imgView2.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.photo));
    // Drawableを設定
    ImageView imgView3 = (ImageView)findViewById(R.id.imgview3_id);
    imgView3.setImageDrawable(getResources().getDrawable(R.drawable.photo));
  }
}





コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

Menu


逆引き(基礎編)

画面表示/操作(49)

フラグメント(1)

逆引き(応用編)

Firebase(2)

AD



管理人/副管理人のみ編集できます