首页 > 代码库 > Spinner的功能和用法

Spinner的功能和用法

Gallery和Spinner的共同父类是: AbsSpinner。他们都是列表框,区别有二:

1、Spinner显示的是垂直的列表框,而Gallery显示的是水平的列表框;

2、Spinner的作用是供用户选择,Gallery是用户拖动来查看上一个下一个列表项;

举个例子来分别说明Spinner的用法;Galler是不推荐的控件!

sample1(Spinner):

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.hct.spinner.MainActivity" >    <Spinner        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:entries="@array/books" />    <Spinner        android:id="@+id/spinner"        android:layout_width="fill_parent"        android:layout_height="wrap_content" /></LinearLayout>

MainActivity.java:

 1 public class MainActivity extends Activity { 2  3     private Spinner m_spinner; 4  5     @Override 6     protected void onCreate(Bundle savedInstanceState) { 7         super.onCreate(savedInstanceState); 8         setContentView(R.layout.activity_main); 9         m_spinner = (Spinner) findViewById(R.id.spinner);10         String[] arr = new String[] { "孙悟空", "猪八戒", "唐僧" };11 12         ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,13                 android.R.layout.simple_list_item_multiple_choice, arr);14         m_spinner.setAdapter(adapter);15     }16 17     @Override18     public boolean onCreateOptionsMenu(Menu menu) {19         // Inflate the menu; this adds items to the action bar if it is present.20         getMenuInflater().inflate(R.menu.main, menu);21         return true;22     }23 24     @Override25     public boolean onOptionsItemSelected(MenuItem item) {26         // Handle action bar item clicks here. The action bar will27         // automatically handle clicks on the Home/Up button, so long28         // as you specify a parent activity in AndroidManifest.xml.29         int id = item.getItemId();30         if (id == R.id.action_settings) {31             return true;32         }33         return super.onOptionsItemSelected(item);34     }35 }