1.Spinner類簡介
Spinner位於android:widget包下,每次只顯示用戶選中的元素,當用戶再次點擊是,會彈出選擇列表供用戶選擇而選擇列表中的元素同樣來自適配器,它的繼承關系如下:
Java.lang.Object/Adroid.view.View/android.ViewGoup/android.widget.AdapterView/android.widget.AbsSpinner/android.widget.Spinner
2下拉列表使用案例
a.創建項目,並准備圖片資源,將圖片資源存放到項目目錄中的res/drawable-mdpi文件夾下;
b.准備字符串資源;
c.准備顏色資源,在res/values目錄下創建color.xml文件,並寫入代碼;
d.開發該案例的布局文件,即main.xml,如下;
e.開發案例的主要邏輯代碼,如下:
package com.example.sample_5_9; import android.annotation.SuppressLint; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; public class Sample_5_9 extends Activity { final static int WRAP_CONTENT = -2;//表示WRAP_CONTETN 的常量 int[] drawableIds = {R.drawable.football, R.drawable.basketball, R.drawable.volleyball};//所有資源文件 int[] msgIds = {R.string.zq, R.string.lq,R.string.pq};//所有資源字符串 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Spinner sp = (Spinner)this.findViewById(R.id.Spinner01);//初始化Spinner BaseAdapter ba = new BaseAdapter() { public int getCount() { return 3; } public Object getItem(int position) { return null; } public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) {//動態生成每個下拉項對應的View,每個下拉項View由LinearLayout中包含一個ImageView及一個TextView構成 LinearLayout ll = new LinearLayout(Sample_5_9.this); ll.setOrientation(LinearLayout.HORIZONTAL);//設置朝向 ImageView ii = new ImageView(Sample_5_9.this); ii.setImageDrawable(getResources().getDrawable(drawableIds[position]));//設置圖片 ll.addView(ii);//將ImageView添加到LinearLayout中 TextView tv = new TextView(Sample_5_9.this); tv.setText(" "+ getResources().getText(msgIds[position]));//設置內容 tv.setTextSize(24); tv.setTextColor(R.color.black); ll.addView(tv); return ll; } }; sp.setAdapter(ba); sp.setOnItemSelectedListener( new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { TextView tv = (TextView)findViewById(R.id.TextView01); LinearLayout ll = (LinearLayout)arg1; TextView tvn = (TextView)ll.getChildAt(1);
StringBuilder sb = new StringBuilder();
sb.append(getResources().getText(R.string.ys)); sb.append(":"); sb.append(tvn.getText()); tv.setText(sb.toString()); } public void onNothingSelected(AdapterView<?> arg0) { } }); } public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
f.程序運行結果如下: