Android Spinner(スピナー)を使用する その5(SimpleCursorAdapter)

今回はSimpleCursorAdapterを使用してみました。
SimpleCursorAdapterはxmlファイルで定義された複数のビューに対して、CursorオブジェクトのColumnをマッピングする簡単なアダプターです。



1,データベースにデータを作成します。
Android SQLiteデータベースを作成するで作成したDatabaseHelper.javaを使用し、以下のようなテーブルを作成しました。

CREATE TABLE Categories
(
CategoryID integer NOT NULL,
CategoryName text NOT NULL,
Description text,
primary key(CategoryID)
)

あとはInsert文で適当にデータを追加します。
Android データベースにデータを書き込む(Insert、Update、Delete)


2,アクティビティのレイアウトにスピナーを追加します。
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 
 android:id="@+id/LinearLayout01" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:orientation="vertical">
    
<Spinner 
 android:id="@+id/Spinner01" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content"> 
</Spinner>

</LinearLayout>

3,スピナーのレイアウトファイルを作成します。
res/layout/spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:id="@+id/LinearLayout01" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 android:orientation="vertical">
 
<TextView 
 android:id="@+id/text" 
 style="?android:attr/spinnerItemStyle"
 android:singleLine="true"    
    android:layout_width="fill_parent"    
    android:layout_height="wrap_content"    
    android:textSize="14sp"  
    android:ellipsize="marquee" > 
</TextView>

</LinearLayout>
注意点は
・android:idは3で作成するレイアウトのidと同じにすること。
・規定のスタイルを使用する場合は style="?android:attr/spinnerItemStyle"とすること。

4,スピナーのドロップダウンリストのレイアウトファイルを作成します。
res/layout/spinner_dropdown.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:id="@+id/LinearLayout01" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 android:orientation="vertical"> 

 <TextView 
  android:id="@+id/text" 
  style="?android:attr/spinnerDropDownItemStyle"
  android:layout_width="wrap_content" 
  android:layout_height="25sp"
  android:textSize="14sp">   
 </TextView>

 <TextView 
  android:id="@+id/description" 
  style="?android:attr/spinnerDropDownItemStyle"
  android:layout_width="wrap_content" 
  android:layout_height="20sp"
  android:textSize="10sp">
 </TextView>

</LinearLayout>
注意点は
・android:idは2で作成するレイアウトのidと同じにすること。
・規定のスタイルを使用する場合はstyle="?android:attr/spinnerDropDownItemStyle"とすること。

5,アクティビティクラス
SimpleCursorAdapterクラスを使用してスピナーの設定を行います。

SimpleCursorAdapterクラスのコンストラクタ
SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) 
第1引数contextにはContextオブジェクトを指定します。

第2引数layoutはスピナーに使用するレイアウトファイルのIDを指定します。
今回は3で作成したレイアウトファイルを指定します。

第3引数cにはドロップダウンリストに表示するアイテムを指定します。
ドロップダウンリストに表示するアイテムは、データベースから取得したデータのCursorオブジェクトです。
Cursorオブジェクトに「_id」フィールドが含まれていないとエラーになります。

第4引数fromは第3引数で指定したCursorオブジェクトから、表示したいカラム名をString配列で指定します。

第5引数toは第4引数fromで指定したカラムの値をを表示するレイアウトファイル内のViewのIdをint配列で指定します。

またSimpleCursorAdapter#setDropDownViewResource()メソッドでドロップダウンリスト部分に使用するレイアウトファイルのIDを指定します。
既定のレイアウトを使用する場合は、アンドロイドで定義されているandroid.R.layout.simple_spinner_dropdown_itemを指定します。
今回は4で作成したレイアウトファイルを指定します。

あとは作成したAdapterオブジェクトを、Spinner#.setAdapter()メソッドでスピナーに設定します。


データベースのデータを取得するにはAndroid データベースのデータを読み込む(Select)を参考にしてください。

またSimpleCursorAdapterのコンストラクタ引数に指定するCursorオブジェクトには「_id」フィールドが含まれていないとエラーになります。データベースのテーブルに「_id」フィールドを用意するか、SELECT文で「_id」フィールドを追加してください。

今回はSELECT文で「_id」フィールドを追加しました。
package my.study.android;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class MainActivty extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //データベースよりデータを取得します
        DatabaseHelper dbHelper = new DatabaseHelper(this);      
        SQLiteDatabase db = dbHelper.getReadableDatabase();  
        String sql = "SELECT '0' AS _id, CategoryID, CategoryName, Description " +
                     "FROM Categories";
        Cursor cursor = db.rawQuery(sql,null);
        //Adapterを作成します。
        String[] from = {"CategoryName","Description"};
        int[] to = {R.id.text,R.id.description};
        SimpleCursorAdapter adapter = 
            new SimpleCursorAdapter(this,R.layout.spinner,cursor,from,to);
        //ドロップダウンリストのレイアウトを設定します。   
        adapter.setDropDownViewResource(R.layout.spinner_dropdown);   
        //スピナーにadapterを設定します。   
        Spinner spinner  = (Spinner)this.findViewById(R.id.Spinner01);   
        spinner.setAdapter(adapter);
        //スピナーのアイテムが選択された時に呼び出されるコールバックリスナーを登録します   
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView parent, View view, int position, long id) {
                Spinner spinner = (Spinner) parent;   
                Cursor cursor = (Cursor)spinner.getSelectedItem();
                int categoryId = cursor.getInt(cursor.getColumnIndex("CategoryID"));
                Toast.makeText(MainActivty.this,
                    Integer.valueOf(categoryId).toString(),
                    Toast.LENGTH_LONG).show(); 
            }
            public void onNothingSelected(AdapterView parent) {    
            }   
        });   
    }
}


上記の方法で表示したスピナーのドロップダウンリストには、選択しているアイテムをチェック状態で表示するラジオボタンが表示されません。これは4で作成したドロップダウンリストのレイアウトファイルの最上位オブジェクトであるLinearLayoutがCheckableインターフェースを実装していないためだそうです。
ドロップダウンリストにラジオボタンを表示するには前回の記事Android Spinner(スピナー)を使用する その4(SimpleAdapter)を参考にしてください。


【関連項目】
Android Spinner(スピナー)を使用する その1
Android Spinner(スピナー)を使用する その2(ArrayAdapter)
Android Spinner(スピナー)を使用する その3(UIカスタマイズ)
Android Spinner(スピナー)を使用する その4(SimpleAdapter)
Android Spinner(スピナー)を使用する その5(SimpleCursorAdapter)

Android Spinner(スピナー)を使用する その4(SimpleAdapter)

今回はSimpleAdapterを使用してみました。
SimpleAdapterはxmlファイルで定義された複数のビューに対して、データをマッピングする簡単なアダプターです。


1,アクティビティのレイアウトにスピナーを追加します。
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 
 android:id="@+id/LinearLayout01" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:orientation="vertical">
    
<Spinner 
 android:id="@+id/Spinner01" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
</Spinner>

</LinearLayout>

2,スピナーのレイアウトファイルを作成します。
res/layout/spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:id="@+id/LinearLayout01" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 android:orientation="vertical">
 
<TextView 
 android:id="@+id/text" 
 style="?android:attr/spinnerItemStyle"
 android:singleLine="true"    
    android:layout_width="fill_parent"    
    android:layout_height="wrap_content"    
    android:textSize="14sp"  
    android:ellipsize="marquee" > 
</TextView>
</LinearLayout>
注意点は
・android:idは3で作成するレイアウトのidと同じにすること。
・規定のスタイルを使用する場合は style="?android:attr/spinnerItemStyle"とすること。


3,スピナーのドロップダウンリストのレイアウトファイルを作成します。
res/layout/spinner_dropdown.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:id="@+id/LinearLayout01" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 android:orientation="vertical"> 
<TextView 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:id="@+id/text" 
 style="?android:attr/spinnerDropDownItemStyle"
 android:singleLine="true" 
 android:layout_width="fill_parent" 
 android:textSize="14sp"
 android:ellipsize="marquee" 
       android:layout_height="25sp">
</TextView> 
<TextView 
 android:id="@+id/description" 
 style="?android:attr/spinnerDropDownItemStyle"
 android:singleLine="true" 
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:textSize="10sp"
 android:ellipsize="marquee">
</TextView>

</LinearLayout>
注意点は
・android:idは2で作成するレイアウトのidと同じにすること。
・規定のスタイルを使用する場合はstyle="?android:attr/spinnerDropDownItemStyle"とすること。

4,アクティビティクラス
SimpleAdapterクラスを使用してスピナーの設定を行います。

SimpleAdapterクラスのコンストラクタ
SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) 
第1引数contextにはContextオブジェクトを指定します。

第2引数dataにはドロップダウンリストに表示するアイテムを指定します。
ドロップダウンリストに表示するアイテムは、Mapインターフェースを格納したListインターフェースになっています。

第3引数resourceはスピナーに使用するレイアウトファイルのIDを指定します。
今回は2で作成したレイアウトファイルを指定します。

第4引数fromは第2引数dataで指定したListの要素であるMapから、表示したい要素のキーをString配列で指定します。

第5引数toは第4引数fromで指定したキーの値をを表示するレイアウトファイル内のViewのIdをint配列で指定します。


またSimpleAdapter#setDropDownViewResource()メソッドでドロップダウンリスト部分に使用するレイアウトファイルのIDを指定します。
既定のレイアウトを使用する場合は、アンドロイドで定義されているandroid.R.layout.simple_spinner_dropdown_itemを指定します。
今回は3で作成したレイアウトファイルを指定します。

あとは作成したAdapterオブジェクトを、Spinner#.setAdapter()メソッドでスピナーに設定します。

MainActivty.java
package my.study.android2;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class MainActivity extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  
        //ドロップダウンデータの作成
        ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        //item1
        map = new HashMap<String, Object>();
        map.put("value",10);
        map.put("text","item1");
        map.put("description","description1");
        items.add(map); 
        //item2
        map = new HashMap<String, Object>();
        map.put("value",20);
        map.put("text","item2");
        map.put("description","description2");
        items.add(map);
        //item3
        map = new HashMap<String, Object>();
        map.put("value",30);
        map.put("text","item3");
        map.put("description","description3");
        items.add(map);
  
        //SimpleAdapterオブジェクトの作成
        SimpleAdapter adapter = new SimpleAdapter(this,items,R.layout.spinner,
                new String[]{"text","description"},
                new int[]{R.id.text,R.id.description});
 
        //ドロップダウンリストのレイアウトを設定します。
        adapter.setDropDownViewResource(R.layout.spinner_dropdown);
        //スピナーにadapterを設定します。
        Spinner spinner  = (Spinner)this.findViewById(R.id.Spinner01);
        spinner.setAdapter(adapter);
        //スピナーのアイテムが選択された時に呼び出されるコールバックリスナーを登録します
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View arg1, int position, long id) {
                Spinner spinner = (Spinner) parent;
                HashMap<String, Object> item = (HashMap<String, Object>) spinner.getSelectedItem();  
                Toast.makeText(MainActivity.this, item.get("value").toString(), Toast.LENGTH_LONG).show();
            }
            public void onNothingSelected(AdapterView<?> parent) {   
            }
        });
    }
}

ドロップダウンリストにラジオボタンを表示する

上記の方法で表示したスピナーのドロップダウンリストには、選択しているアイテムをチェック状態で表示するラジオボタンが表示されません。これは3で作成したドロップダウンリストのレイアウトファイルの最上位オブジェクトであるLinearLayoutがCheckableインターフェースを実装していないためだそうです。
こちらで詳しく解説されています。
だらだらとだらだら AndroidのAdapterViewで、カスタムビューを使っていてもCheckedTextViewなどのチェックをしたい(Spinnerのdropdown等)

次はドロップダウンリストにラジオボタンを表示したいと思います。

1,まずはCheckableインターフェースを実装したLinearLayoutを作成します。
src/my.study.android.widgets/CheckableLinearLayout.jar
package my.study.android.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Checkable;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;

public class CheckableLinearLayout extends LinearLayout implements Checkable {
 
    private CheckedTextView mCheckbox;
 
    public CheckableLinearLayout(Context context) {
        super(context);
    }
    public CheckableLinearLayout(Context context, AttributeSet attrs) {        
        super(context, attrs); 
    }
    @Override    
    protected void onFinishInflate() {
        super.onFinishInflate();
        // CheckedTextViewを探します。
        int childCount = getChildCount();
        for (int i = 0; i < childCount; ++i) {
            View v = getChildAt(i);
            if (v instanceof CheckedTextView) {
                mCheckbox = (CheckedTextView)v;   
            }  
        }         
    }
    public boolean isChecked() {
        return mCheckbox != null ? mCheckbox.isChecked() : false;   
    }
    public void setChecked(boolean checked) {
        if (mCheckbox != null) {
            mCheckbox.setChecked(checked);     
        }      
    }

    public void toggle() {
        if (mCheckbox != null) {
            mCheckbox.toggle();     
        }      
    }   
}

2,スピナーのドロップダウンリストのレイアウトファイルを作成します。
res/layout/spinner_dropdown.xml
<?xml version="1.0" encoding="utf-8"?>
<my.study.android.widgets.CheckableLinearLayout 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:id="@+id/LinearLayout01" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 android:orientation="horizontal"> 
 
<LinearLayout 
 android:id="@+id/LinearLayout02" 
 android:layout_height="wrap_content" 
 android:orientation="vertical" 
 android:layout_width="wrap_content"
 android:layout_weight="1">

 <TextView 
  android:text="@+id/TextView02" 
  android:id="@+id/text" 
  style="?android:attr/spinnerDropDownItemStyle"
  android:layout_width="wrap_content" 
  android:layout_height="25sp"
  android:textSize="14sp">   
 </TextView>

 <TextView 
  android:text="@+id/TextView01" 
  android:id="@+id/description" 
  style="?android:attr/spinnerDropDownItemStyle"
  android:layout_width="wrap_content" 
  android:layout_height="20sp"
  android:textSize="10sp">
 </TextView>
</LinearLayout>

<CheckedTextView 
 android:id="@+id/CheckedTextView01" 
 style="?android:attr/spinnerDropDownItemStyle"
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content">
</CheckedTextView>

</my.study.android.widgets.CheckableLinearLayout>

MainActivity.java、Spinner.xmlの変更はありません。


【関連項目】
Android Spinner(スピナー)を使用する その1
Android Spinner(スピナー)を使用する その2(ArrayAdapter)
Android Spinner(スピナー)を使用する その3(UIカスタマイズ)
Android Spinner(スピナー)を使用する その4(SimpleAdapter)
Android Spinner(スピナー)を使用する その5(SimpleCursorAdapter)

Android Spinner(スピナー)を使用する その3(UIカスタマイズ)

今回はスピナーのレイアウトを変更したいと思います。

複数行を表示できるようにする


1,アクティビティのレイアウトにスピナーを追加します。
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 
 android:id="@+id/LinearLayout01" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:orientation="vertical">
    
<Spinner 
 android:id="@+id/Spinner01" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
</Spinner>

</LinearLayout>

2,スピナーのレイアウトファイルを作成します。
res/layout/spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:id="@android:id/text2" 
    style="?android:attr/spinnerItemStyle" 
    android:singleLine="false" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textSize="12sp"
    android:ellipsize="marquee" >
</TextView>
改行を表示できるようにするため「android:singleLine="false" 」を指定します。
その他いくつか注意点があります。
・android:idは3で作成するレイアウトのidと同じにすること。
・android:idは"@android:id/text1"または"@android:id/text2"にすること。
(android.R.idで定義されているのidがtext1またはtext2であるため)
・規定のスタイルを使用する場合は style="?android:attr/spinnerItemStyle"とすること。


3,スピナーのドロップダウンリストのレイアウトファイルを作成します。
res/layout/spinner_dropdown.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:id="@android:id/text1" 
    style="?android:attr/spinnerDropDownItemStyle"
    android:layout_height="?android:attr/listPreferredItemHeight" 
    android:singleLine="false" 
    android:layout_width="fill_parent"
 android:textSize="13sp"
    android:ellipsize="marquee" >
</CheckedTextView>
改行を表示できるようにするため「android:singleLine="false" 」を指定します。
注意点は
・android:idは2で作成するレイアウトのidと同じにすること。
・android:idは"@android:id/text1"または"@android:id/text2"にすること。
(android.R.idで定義されているのidがtext1またはtext2であるため)
・規定のスタイルを使用する場合はstyle="?android:attr/spinnerDropDownItemStyle"とすること。

4,アクティビティクラス
ArrayAdapterクラスを使用してスピナーの設定を行います。

ArrayAdapterクラスのコンストラクタは以下のようなものがあります。
ArrayAdapter(Context context, int textViewResourceId) 
ArrayAdapter(Context context, int textViewResourceId, T[] objects) 
ArrayAdapter(Context context, int textViewResourceId, List objects)
第1引数contextにはContextオブジェクトを指定します。

第2引数textViewResourceIdにはスピナーに使用するレイアウトファイルのIDを指定します。
既定のレイアウトを使用する場合は、アンドロイドで定義されているandroid.R.layout.simple_spinner_itemを指定します。
今回は2で作成したレイアウトファイルを指定します。

第3引数objectはドロップダウンリストに表示するアイテムを指定します。
ドロップダウンリストに表示するアイテムはObject型の配列かList インターフェイス実装クラスになっています。
それぞれの要素がCharSequence インターフェイスを実装したクラスである場合は、指定した値をそのまま表示しますが
そうでなければ要素のtoString()の結果を出力します。


またArrayAdapter#setDropDownViewResource()メソッドでドロップダウンリスト部分に使用するレイアウトファイルのIDを指定します。
既定のレイアウトを使用する場合は、アンドロイドで定義されているandroid.R.layout.simple_spinner_dropdown_itemを指定します。
今回は3で作成したレイアウトファイルを指定します。

あとは作成したAdapterオブジェクトを、Spinner#.setAdapter()メソッドでスピナーに設定します。

MainActivty.java
package my.study.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivty extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
   
        //ArrayAdapterを作成
        ArrayAdapter adapter = 
    new ArrayAdapter(this,R.layout.spinner);
        //ドロップダウンリストのレイアウトを設定      
        adapter.setDropDownViewResource(R.layout.spinner_dropdown);
        //ドロップダウンアイテムの追加
        adapter.add("item1\nDescription1");
        adapter.add("item2\nDescription2");
        adapter.add("item3\nDescription3");
        //スピナーにadapterを設定
        Spinner spinner = (Spinner)this.findViewById(R.id.Spinner01);
        spinner.setAdapter(adapter);
  
    }
}

ドロップダウンのアイコンを変更する


1,画像ファイルを配置します。
解像度に合わせてres/drawable-hdpi, res/drawable-mdpi, res/drawable-ldpiに、選択している時の画像と選択していないときの画像を配置します。
今回は選択された時の画像としてstar_big_on.png、選択していない時の画像としてstart_big_off.pngを追加しました。

star_big_on.png

star_big_off.png

2,画像のSelectorを作成します。
res/drawable-hdpi, res/drawable-mdpi, res/drawable-ldpiのそれぞれに、状態に応じて画像を選択するselectorファイルを作成します。
res/drawable-xdpi/spinner_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
 <item
  android:state_checked="true"
  android:drawable="@drawable/star_big_on" />
 <item 
  android:state_checked="false"       
  android:drawable="@drawable/star_big_off" />
</selector>

3,スタイルファイルを作成します。
先ほど作成したselectorファイルを指定するスタイルファイルを作成します。
res/values/styles.xml
<?xml version="1.0" encoding="UTF-8"?>
<resources >
    <style name="SpinnerDropDownIcon" parent="android:Widget.DropDownItem.Spinner">
        <item name="android:checkMark">@drawable/spinner_selector</item>
    </style>
</resources>

4,スピナーのドロップダウンリストのレイアウトファイルを作成します。
res/layout/spinner_dropdown.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:id="@android:id/text1" 
    style="@style/SpinnerDropDownIcon"
    android:layout_height="?android:attr/listPreferredItemHeight" 
    android:singleLine="false" 
    android:layout_width="fill_parent"
 android:textSize="13sp"
    android:ellipsize="marquee" >
</CheckedTextView>
styleには3で作成したスタイルファイルを指定します。

5.スピナーのレイアウトファイルを作成します。
res/layout/spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView  
    xmlns:android="http://schemas.android.com/apk/res/android"  
    android:id="@android:id/text2" 
    style="?android:attr/spinnerItemStyle" 
    android:singleLine="false" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:textSize="12sp"
    android:ellipsize="marquee" >
</TextView>

6.アクティビティクラス
MainActivty.java
package my.study.android;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivty extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
   
        //ArrayAdapterを作成
        ArrayAdapter adapter = 
    new ArrayAdapter(this,R.layout.spinner);
        //ドロップダウンリストのレイアウトを設定      
        adapter.setDropDownViewResource(R.layout.spinner_dropdown);
        //ドロップダウンアイテムの追加
        adapter.add("item1\nDescription1");
        adapter.add("item2\nDescription2");
        adapter.add("item3\nDescription3");
        //スピナーにadapterを設定
        Spinner spinner = (Spinner)this.findViewById(R.id.Spinner01);
        spinner.setAdapter(adapter);
  
    }
}

【関連項目】
Android Spinner(スピナー)を使用する その1
Android Spinner(スピナー)を使用する その2(ArrayAdapter)
Android Spinner(スピナー)を使用する その3(UIカスタマイズ)
Android Spinner(スピナー)を使用する その4(SimpleAdapter)
Android Spinner(スピナー)を使用する その5(SimpleCursorAdapter)

Android Spinner(スピナー)を使用する その2(ArrayAdapter)

前回Android Spinner(スピナー)を使用する その1
はスピナーのドロップダウンリストに表示する各アイテムをリソースファイルで定義しましたが、今回はArrayAdapterクラスを利用してコードから指定したいと思います。


1,アクティビティのレイアウトにスピナーを追加します。
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 
 android:id="@+id/LinearLayout01" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:orientation="vertical">
    
<Spinner 
 android:id="@+id/Spinner01" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
</Spinner>

</LinearLayout>

2,スピナーのドロップダウンリストに表示するプロンプトを定義します。
res/values/strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="SpinnerPrompt">選択してください。</string>
        :
</resources>

3,アクティビティクラス
ArrayAdapterクラスを使用してスピナーの設定を行います。

ArrayAdapterクラスのコンストラクタは以下のようなものがあります。
ArrayAdapter(Context context, int textViewResourceId) 
ArrayAdapter(Context context, int textViewResourceId, T[] objects) 
ArrayAdapter(Context context, int textViewResourceId, List objects)
第1引数contextにはContextオブジェクトを指定します。

第2引数textViewResourceIdにはスピナーに使用するレイアウトファイルのIDを指定します。
今回はtextViewResourceIdには、アンドロイドで定義されているandroid.R.layout.simple_spinner_itemを指定します。

第3引数objectはドロップダウンリストに表示するアイテムを指定します。
ドロップダウンリストに表示するアイテムはObject型の配列かList インターフェイス実装クラスになっています。
それぞれの要素がCharSequence インターフェイスを実装したクラスである場合は、指定した値をそのまま表示しますが
そうでなければ要素のtoString()の結果を出力します。


またArrayAdapter#setDropDownViewResource()メソッドでドロップダウンリスト部分に使用するレイアウトファイルのIDを指定します。
今回は、アンドロイドで定義されているandroid.R.layout.simple_spinner_dropdown_itemを指定します。

あとは作成したAdapterオブジェクトを、Spinner#.setAdapter()メソッドでスピナーに設定します。

MainActivty.java
package my.study.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;


public class MainActivty extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  
        // ArrayAdapter を作成  
        String items[] = {"items1","items2","items3"};
        ArrayAdapter<String> adapter
                = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
        //または
        //ArrayAdapter<String> adapter
        //        = new ArrayAdapter<string>(this, android.R.layout.simple_spinner_item)
        //adapter.add("item1");
        //adapter.add("item2");
        //adapter.add("item3");
        
        // ドロップダウンリストのレイアウトを設定   
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
         
        //spinnerにAdapterを設定
        Spinner spinner  = (Spinner)this.findViewById(R.id.Spinner01);
        spinner.setAdapter(adapter);
        // Spinner に表示させるプロンプトを設定   
        spinner.setPromptId(R.string.SpinnerPrompt );
  
        // スピナーのアイテムが選択された時に呼び出されるコールバックリスナーを登録します
        spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
            //Spinnerのドロップダウンアイテムが選択された時
            public void onItemSelected(AdapterView parent, View viw, int arg2, long arg3) {
                Spinner spinner = (Spinner)parent;
                String item = (String)spinner.getSelectedItem();
                Toast.makeText(MainActivty.this, item, Toast.LENGTH_LONG).show();
            }
            //Spinnerのドロップダウンアイテムが選択されなかった時
            public void onNothingSelected(AdapterView parent) {
            }});
    }
}

【関連項目】
Android Spinner(スピナー)を使用する その1
Android Spinner(スピナー)を使用する その2(ArrayAdapter)
Android Spinner(スピナー)を使用する その3(UIカスタマイズ)
Android Spinner(スピナー)を使用する その4(SimpleAdapter)
Android Spinner(スピナー)を使用する その5(SimpleCursorAdapter)

Android Spinner(スピナー)を使用する その1

Spinnerはクリックするとリストが表示され、そこから項目を選択することができる、Windowsのコンボボックスのようなものです。

まずは基本的な使い方から。

1,スピナーのドロップダウンアイテムに設定する文字列の配列を定義します。
res/values/arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

<string-array name="SpinnerItems">
 <item>Item1</item>
 <item>Item2</item>
 <item>Item3</item>
</string-array>

</resources>

2,アクティビティのレイアウトにスピナーを追加します。
res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 
 android:id="@+id/LinearLayout01" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 xmlns:android="http://schemas.android.com/apk/res/android" 
 android:orientation="vertical">
    
<Spinner 
 android:id="@+id/Spinner01" 
 android:layout_width="wrap_content" 
 android:layout_height="wrap_content" 
 android:entries="@array/SpinnerItems" 
 android:prompt="@string/SpinnerPrompt">
</Spinner>

</LinearLayout>
entriesプロパティで1で作成した文字列配列を指定します。
SpinnerPromptプロパティでドロップダウンに表示するプロンプトを指定します。
ここではres/values/strings.xmlに指定した値を使用しています。
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="SpinnerPrompt">選択してください。</string>
        :
</resources>

3,アクティビティクラスでスピナーのアイテムが選択された時に呼び出されるコールバックリスナーを登録します。
package my.study.android;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class MainActivty extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // スピナーのアイテムが選択された時に呼び出されるコールバックリスナーを登録します        
        Spinner spinner = (Spinner)this.findViewById(R.id.Spinner01);
        spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
            //Spinnerのドロップダウンアイテムが選択された時
            public void onItemSelected(AdapterView parent, View viw, int arg2, long arg3) {
                Spinner spinner = (Spinner)parent;
                String item = (String)spinner.getSelectedItem();
                Toast.makeText(MainActivty.this, item, Toast.LENGTH_LONG).show();
            }
            //Spinnerのドロップダウンアイテムが選択されなかった時
            public void onNothingSelected(AdapterView parent) {
            }});
    }
}

【関連項目】
Android Spinner(スピナー)を使用する その1
Android Spinner(スピナー)を使用する その2(ArrayAdapter)
Android Spinner(スピナー)を使用する その3(UIカスタマイズ)
Android Spinner(スピナー)を使用する その4(SimpleAdapter)
Android Spinner(スピナー)を使用する その5(SimpleCursorAdapter)