Spinnerのサブアイテムを使ってみました。
※はじめに
この記事はAndroidアプリの開発が、初心者であるという方のための記事です。
そのため、なるべく複雑な説明は避け、コピー&ペイストですぐに動くものをご紹介します。
JavaやAndroidを理解されている方で細かい説明が必要な方は、当ブログ内の連載記事である「Android Tips」をご覧ください。
さて、SpinnerもListViewと同様に、サブアイテムを使用することができます。
やり方は複数存在しますが、ここでは極力ListViewに近い状態で作っています。
サンプルコード
アプリ実行図
画面レイアウトファイル(activity_main.xml)
アプリの画面レイアウトファイルです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | android:layout_width = "match_parent" android:layout_height = "match_parent" android:padding = "15dp" android:orientation = "vertical" tools:context = ".MainActivity" > < Spinner android:id = "@+id/spinner1" android:layout_width = "wrap_content" android:layout_height = "wrap_content" /> < TextView android:id = "@+id/textView1" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "未選択" /> </ LinearLayout > |
Activityファイル(MainActivity.java)
Activityファイルです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | package com.example.spinnersubitem; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.SimpleAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnItemSelectedListener { private Spinner spinner; private TextView textView; private String[] text = { "Excel" , "Word" , "Outlook" }; private String[] description = { "表計算" , "書類" , "メール" }; private Map<String, String> map; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); ArrayList<Map<String, String>> items = new ArrayList<Map<String, String>>(); for ( int i = 0 ; i < text.length; i++) { map = new HashMap<String, String>(); map.put( "text" , text[i]); map.put( "description" , description[i]); items.add(map); } SimpleAdapter adapter = new SimpleAdapter( this , items, android.R.layout.simple_list_item_2, new String[] { "text" , "description" }, new int [] { android.R.id.text1, android.R.id.text2 }); spinner = (Spinner) findViewById(R.id.spinner1); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener( this ); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { map = (Map<String, String>) parent.getItemAtPosition(position); String str = map.get( "text" ); Toast.makeText( this , str, Toast.LENGTH_SHORT).show(); textView = (TextView) findViewById(R.id.textView1); textView.setText(str); } @Override public void onNothingSelected(AdapterView<?> parent) { } } |
以上でOKです。