ImageButtonクラスの定義とコンストラクタ

広告

ImageButtonクラスの定義を確認します。クラス図は次のようになっています。

java.lang.Object
  android.view.View
    android.widget.ImageView
      android.widget.ImageButton

ImageButtonクラスはImageViewクラスのサブクラスです。画像を扱うビューの一つでありボタンの形状を持つビューとなります。

ImageButtonクラスのコンストラクタ

ImageButtonクラスを利用するにはコンストラクタを使ってImageButtonクラスのオブジェクトを作成します。どのようなコンストラクタが用意されているか確認してみます。

コンストラクタ
ImageButton(Context context)
ImageButton(Context context, AttributeSet attrs, Map inflateParams)
ImageButton(Context context, AttributeSet attrs, Map inflateParams, int defStyle)

コンストラクタは3つ用意されています。1番目のコンストラクタ以外は詳細は不明です。

1番目のコンストラクタの場合、引数には「Context」クラスのオブジェクトを指定します。ここでは自分自身を表す「this」を指定して下さい(画面を作成する「Activity」クラスは「Context」クラスのサブクラスとなっており、作成しているクラスは「Activity」クラスを継承して作成しています。すなわち作成しているクラスは「Context」クラスのサブクラスです)。

具体的には次のように記述します。

private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 

@Override public void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    ImageButton imgbutton = new ImageButton(this);
    setContentView(imgbutton, new LayoutParams(WC, WC));
}

では次のページ以降で「ImageButton」クラスの詳しい使い方を確認していきます。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。