Spinner
下拉式選單的用法與之前所提到的 Button 或是 CheckBox 等方式略有不同,下拉式選單可以利用 Adapter 將選項與物件綁在一起,而 Adapter 本身的角色則提供了一系列的操作,可以方便於選項的增刪選擇,此處所使用的是 ArrayAdapter ,與之綁定的資料為字串陣列,最後再將此 Adapter 設定給下拉式選單,即完成了 Spinner、Adapter與資料三者的綁定。此範例的功能為選擇每一個顏色後,即在上方的 TextView上顯示。
原始碼
package nchu.test; 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.TextView; public class test extends Activity { private static final String[] m_colors ={"red","blue","white"}; private TextView m_textview; private Spinner m_spinner; private ArrayAdapteradapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); m_textview = (TextView)findViewById(R.id.textView1); m_spinner = (Spinner)findViewById(R.id.spinner1); adapter = new ArrayAdapter (this,android.R.layout.simple_spinner_dropdown_item,m_colors); m_spinner.setAdapter(adapter); m_spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) { m_textview.setText("顏色:" + m_colors[arg2]); } @Override public void onNothingSelected(AdapterView arg0) { // TODO Auto-generated method stub } }); } }
AutoCompleteTextView、MultiAutoCompleteTextView
自動完成的部分,Android預設提供兩種,一種是單一的自動完成,意思是一次只能完成一個字詞;另一種就是在一行內可以完成多次的字詞選擇。
自動完成也可以利用 ArrayAdapter 將預設的字詞與功能做綁定,在這裡的範例所使用的自動完成字詞有 apple、car、mouse 和 fish。比較需要注意的是 MultiAutoCompleteTextView 需要設定分隔符號才能正常運作。
原始碼
package nchu.test; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.MultiAutoCompleteTextView; public class test extends Activity { private static final String[] autostr = new String []{ "apple","car","mouse","fish" }; private AutoCompleteTextView m_autoCT; private MultiAutoCompleteTextView m_mautoCT; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ArrayAdapteradapter = new ArrayAdapter (this,android.R.layout.simple_dropdown_item_1line,autostr); m_autoCT = (AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1); m_mautoCT = (MultiAutoCompleteTextView)findViewById(R.id.multiAutoCompleteTextView1); m_autoCT.setAdapter(adapter); m_mautoCT.setAdapter(adapter); m_mautoCT.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer()); } }
DatePicker, TimePicker
Menu
Dialog
ImageView
ImageButton
Gallery
ImageSwitcher
ProgressBar
SeekBar
GridView
ScrollView
ListView