ArrayAdapterクラスを使ってギャラリーのデータを登録

広告

Galleryクラスのオブジェクトを作成した時に表示されるデータを登録する方法を確認します。「Gallery」クラスで用意されている「setAdapter」メソッドを使います。

The Adapter is used to provide the data which backs this Spinner. It also 
provides methods to transform spinner items based on their position 
relative to the selected item.

Parameters:
  adapter  The SpinnerAdapter to use for this Spinner

1番目の引数には「android.widget.SpinnerAdapter」インターフェースを実装したクラスのオブジェクトを指定します。SpinnerAdapterインターフェースを実装したクラスはいくつか用意されていますが、今回は「ArrayAdapter」クラスのオブジェクトを使ってみます。

※「ArrayAdapter」クラスの詳細については「ArrayAdapterクラス」を参照して下さい。

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

private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT; 
private String[] data = {"Apple", "Lemon", "Orange", "Strawberry"}; 

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

    ArrayAdapter<String> arrayAdapter
        = new ArrayAdapter<String>(this, R.layout.rowdata, data);

    Gallery gallery  = new Gallery(this);
    gallery.setAdapter(arrayAdapter);
    setContentView(gallery, new LayoutParams(WC, WC));
}

サンプルプログラム

それでは実際に試してみます。プロジェクトを作成しソースコードを次のように変更しました。

Test02_01.java

package jp.javadrive.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Gallery;
import android.graphics.Color;

public class Test02_01 extends Activity
{
    private final int FP = ViewGroup.LayoutParams.FILL_PARENT;
    private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;

    private String[] data = {"Orange", "Apple", "Melon", "Lemon"};

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

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setBackgroundColor(Color.DKGRAY);
        setContentView(linearLayout);

        Gallery gallery  = new Gallery(this);
        gallery.setBackgroundColor(Color.WHITE);
        linearLayout.addView(gallery, createParam(100, WC));

        ArrayAdapter<String> arrayAdapter
            = new ArrayAdapter<String>(this, R.layout.rowdata, data);

        gallery.setAdapter(arrayAdapter);
    }

    private LinearLayout.LayoutParams createParam(int w, int h){
        return new LinearLayout.LayoutParams(w, h);
    }
}

またレイアウトXMLファイルをリソースとしてプロジェクト内の「res/layout」ディレクトリに配置しました。ファイル名は「rowdata.xml」です。ファイルには次のように記述します。

ArrayAdapterクラスを使ってギャラリーのデータを登録

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
/>

ビルド後にエミュレーター上で実行します。

ArrayAdapterクラスを使ってギャラリーのデータを登録

ギャラリーが作成されて表示されました。エミュレーター上の矢印キーをクリックすると表示データを切り替えることができます。

ArrayAdapterクラスを使ってギャラリーのデータを登録

現在選択されている項目が中央に表示され、その左右に前後の項目の一部が表示されています。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

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