[转]Spinner的常用技巧

本文转自:http://blog.csdn.net/wanli_smile/article/details/6410388

 

用法 1 :以资源方式,静态展示 Spinner 选项

1.     在资源文件 (strings.xml) 中,增加:

         < string name = "spin_prompt" > 请选择城市 </ string >

         < string-array name = "cities" >

                   < item > 北京 </ item >

                   < item > 上海 </ item >

                   < item > 南京 </ item >

                   < item > 乌鲁木齐 </ item >

                   < item > 哈尔滨 </ item >

                   < item > 符拉迪沃斯托克 </ item >

         </ string-array >

 

2.     在布局文件 (main.xml) 中,增加:

         < Spinner

                   android:id = "@+id/Spinner01"

                   android:layout_width = "wrap_content"

                   android:layout_height = "wrap_content"

                   android:entries = "@array/cities"

                   android:prompt = "@string/spin_prompt"

         />

         注意: android:prompt 必须要引用 strings.xml 中资源 ID ,而不能在这里直接用 raw text 。

 

         运行结果:


 

 

点击Spinner右边的带倒三角的按钮,即出现各城市选项如下:

 


用法 2 :以代码方式,动态展示 Spinner 选项

1.     在资源文件 strings.xml 中,无需定义任何资源。

2.     在布局文件 (main.xml) 中, Spinner 的描述为:

         < Spinner

                   android:id = "@+id/Spinner01"

                   android:layout_width = "wrap_content"

                  android:layout_height = "wrap_content"

         />

3.     在 Activity 对应的代码中做相关修改,使之如下:

public class ControlSpinner extends Activity

{

                   private static final String tag = "ControlSpinner" ;

                   private static final String[] cities =

                            { " 上海 " , " 北京 " , " 南京 " , " 哈尔滨 " , " 乌鲁木齐 " , " 符拉迪沃斯托克 " , " 圣弗朗西斯科 " };
 
               private Spinner spinner ;

               @Override

               public void onCreate(Bundle savedInstanceState)

               {

                    super .onCreate(savedInstanceState);

                    setContentView(R.layout. main );

 

                    ArrayAdapter<String> adapter = new ArrayAdapter<String>( this , android.R.layout. simple_spinner_item , cities );
 
//      ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
 
//      adapter.add(" 上海 ");

//      adapter.add(" 北京 ");

//      adapter.add(" 南京 ");

//      adapter.add(" 哈尔滨 ");

//      adapter.add(" 乌鲁木齐 ");

//      adapter.add(" 符拉迪沃斯托克 ");

//      adapter.add(" 圣弗朗西斯科 ");

                    adapter.setDropDownViewResource(android.R.layout. simple_spinner_dropdown_item );
 
                    spinner = (Spinner) this .findViewById(R.id. Spinner01 );

           spinner .setAdapter(adapter);

                    spinner .setPrompt( " 请选择城市 : " );

               }

                   … …

         }

         运行效果和用法 1 相同。

 

         注意:

1.     被注释的代码可以代替

private static final String[] cities = { " 上海 " , " 北京 " , " 南京 " , " 哈尔滨 " , " 乌鲁木齐 " , " 符拉迪沃斯托克 " , " 圣弗朗西斯科 " };
 

ArrayAdapter<String> adapter = new ArrayAdapter<String>( this , android.R.layout. simple_spinner_item , cities );
 
两条语句的组合。

2.     ArrayAdapter 构造函数中的第二个参数是 android.R.layout. simple_spinner_item , adapter.setDropDownViewResource 中的参数则是 android.R.layout. simple_spinner_dropdown_item 。它们是不一样的。
 
 

 

用法 3 :混合方式

1.     在资源文件 (strings.xml) 中,相关的资源描述为:

 

2.     在布局文件 (main.xml) 中, Spinner 的描述为:

         < Spinner

                   android:id = "@+id/Spinner01"

                   android:layout_width = "wrap_content"

                   android:layout_height = "wrap_content"

         />

3.     在 Activity 对应的代码中做相关修改,使之如下:

public class ControlSpinner extends Activity

{

               private Spinner spinner ;

               @Override

               public void onCreate(Bundle savedInstanceState)

               {

                    super .onCreate(savedInstanceState);

                    setContentView(R.layout. main );

 

                    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource ( this ,

                             R.array. cities ,

                             android.R.layout. simple_spinner_item );

                    adapter.setDropDownViewResource(android.R.layout. simple_spinner_dropdown_item );
 
                    spinner = (Spinner) this .findViewById(R.id. Spinner01 );

                    spinner .setAdapter(adapter);

                    spinner .setPrompt( " 请选择城市: " );

               }

                   … …

         }

运行效果与方法 1 也一样。

 

注意:

1.     ArrayAdapter<CharSequence> adapter 中的模板参数必须为 CharSequence

2.     createFromResource 的第二个参数 R.array.cities 就是在 strings.xml 中定义的资源

 

 

用法 4 :改变 Spinner 对象本身的大小,及其文字的大小和颜色

1.     在布局文件 (main.xml) 中,修改 Spinner 对象的描述如下:

         < Spinner

                   android:id = "@+id/Spinner01"

                   android:layout_width = "160px"

                   android:layout_height = "40px"

         />

这使得 Spinner01 的宽度为 160 个像素,高度为 40 个像素。

2.     创建一个布局文件 spinnerLayout.xml ,使之如下:

<? xml version = "1.0" encoding = "utf-8" ?>

         < TextView xmlns:android = "http://schemas.android.com/apk/res/android"

    android:layout_width = "fill_parent"

               android:layout_height = "wrap_content"

               android:textSize = "12sp"         

               android:textColor = "#FF8B1500"

               android:gravity = "center"

         />

3.     在 Activity 对应的代码中做相关修改,使之如下:

public class ControlSpinner extends Activity

{

               private Spinner spinner ;

    @Override

               public void onCreate(Bundle savedInstanceState)

               {

                    super .onCreate(savedInstanceState);

                    setContentView(R.layout. main );

 

                    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource ( this ,

                             R.array. cities ,

                             R.layout. spinnerlayout );                                                                     // 改为 spinnerlayout
 
                    adapter.setDropDownViewResource(R.layout. spinnerlayout );           // 改为 spinnerlayout
 
                    spinner = (Spinner) this .findViewById(R.id. Spinner01 );

                    spinner .setAdapter(adapter);

                    spinner .setPrompt( " 请选择城市 : " );

               }

                   … …

         }

运行结果如下:


 

 


 

 

 

用法5:同时显示图片和文本

假定有澳大利亚、瑞士、中华人民共和国和美利坚合众国这4个国家,我们想把它们的国旗和它们的国名同时显示在Spinner中。

它们对应的国旗图片资源分别如下:


对应的图片文件名分别为: au.png, ch.png, cn.png 和 us.png 。

 

1.     首先把国旗图片拖入 res/drawable-mdpi 文件夹。系统会自动为我们在 R.java 中生成相应的 id 。情形如下:

    public static final class drawable {

        public static final int au=0x7f020000;

        public static final int ch=0x7f020001;

        public static final int cn=0x7f020002;

        public static final int icon=0x7f020004;       // 系统自带的 icon 图标

        public static final int us=0x7f020005;

    }

 

2.     在 strings.xml 中给出各个国家的国名。

         < string name = "au" > 澳大利亚 </ string >

         < string name = "ch" > 瑞士 </ string >

         < string name = "cn" > 中华人民共和国 </ string >

         < string name = "us" > 美利坚合众国 </ string >

 

保存后,系统也会自动为我们在 R.java 中生成相应的 id 。情形如下:

    public static final class string {

        public static final int app_name=0x7f040001;              // 系统自带的 string
 
        public static final int au=0x7f040002;

        public static final int ch=0x7f040003;

        public static final int cn=0x7f040004;

        public static final int us=0x7f040006;

    }

 

3.     假定在布局文件 (main.xml) 中, Spinner01 的属性如下:

         < Spinner

                   android:id = "@+id/Spinner01"

                   android:layout_width = "300px"

                   android:layout_height = "48px"

/>

 

4.     在 Activity 对应的代码中做相关修改,使之如下:

public class ControlSpinner extends Activity

{

               private Spinner spinner ;

                // 国旗图片 ID 数组

               private int [] drawableIDs = {

                        R.drawable. au ,

                        R.drawable. ch ,

                        R.drawable. cn ,

                        R.drawable. us

               };

 

                   // 国名文字 ID 数组

               private int [] nameIDs = {

                        R.string. au ,

                        R.string. ch ,

                        R.string. cn ,

                        R.string. us

               };

   

                   // 自定义一个 Adapter ,要重写 getCount 、 getItem 、 getItemId 和 getView 方法。其中的 getView 方法最为重要。
 
                   // 当然也可以先独立定义一个 Adapter 类

               private BaseAdapter customizedAdapter = new BaseAdapter()

               {

                            public int getCount()

                            {

                                     // TODO Auto-generated method stub

                                     return drawableIDs . length ;

                            }

 

                            public Object getItem( int position)

                            {

                                     // TODO Auto-generated method stub

                                     return drawableIDs [position];

                           }

 

                            public long getItemId( int position)

                           {

                                     // TODO Auto-generated method stub

                                     return position;

                            }

 

                            public View getView( int position, View convertView, ViewGroup parent)
 
                           {

                                     // TODO Auto-generated method stub

                                     // 先设定一个 LinearLayout 对象 ll

                                     LinearLayout ll = new LinearLayout(ControlSpinner. this );
 
                                     // 使 ll 的 Orientation 为 HORIZONTAL

                                     ll.setOrientation(LinearLayout. HORIZONTAL );
 
                                     // 在垂直方向居中

                                     ll.setGravity(Gravity. CENTER_VERTICAL );

                           

                                     // 创建一个 ImageView 对象

                                     ImageView iv = new ImageView(ControlSpinner. this );
 
                                     // 指定对应 position 的 Image

                                     iv.setImageResource( drawableIDs [position]);
 
                                     // 设定 ImageView 对象 iv 的宽度为 100 像素,高度为 40 像素
 
                                     iv.setLayoutParams( new ViewGroup.LayoutParams(100, 40));
 
                                     // 将 iv 加入到 ll

                                     ll.addView(iv);                    

                           

                                     // 创建一个 TextView 对象

                                     TextView tv = new TextView(ControlSpinner. this );
 
                                     // 指定对应 position 的 Text

                                     tv.setText( nameIDs [position]);

                                     // 设定文字大小

                                     tv.setTextSize(14);

                                     // 设定文字颜色

                                     tv.setTextColor(Color. BLUE );

                                     // 将 tv 加入到 ll

                                     ll.addView(tv);

                           

                                     return ll;

                            }

                  };

                  

               @Override

               public void onCreate(Bundle savedInstanceState)

               {

                    super .onCreate(savedInstanceState);

                    setContentView(R.layout. main );

 

                    spinner = (Spinner) this .findViewById(R.id. Spinner01 );

                    spinner .setAdapter( customizedAdapter );

                    spinner .setPrompt( " 请选择国家: " );

               }

                   … …

         }

         运行结果如下:

 运行结果如下:


  如果独立建一个 CustomizedAdapter ,相关代码改写如下:

         class CustomizedAdapter extends BaseAdapter

{

                   private Context ctx ;

                   private int drawableIDs [];

                   private int stringIDs [];

                   public CustomizedAdapter(Context ctx, int DrawableIDs[], int StringIDs[])
 
                   {

                            this . ctx = ctx;

                            this . drawableIDs = DrawableIDs;

                            this . stringIDs = StringIDs;

                   }

        

                   public int getCount()

                   {

                            // TODO Auto-generated method stub

                            return drawableIDs . length ;

                   }

 

                   public Object getItem( int position)

                   {

                            // TODO Auto-generated method stub

                            return drawableIDs [position];

                   }

 

                   public long getItemId( int position)

                   {

                            // TODO Auto-generated method stub

                            return position;

                   }

 

                   public View getView( int position, View convertView, ViewGroup parent)
 
                   {

                            // TODO Auto-generated method stub

                            LinearLayout ll = new LinearLayout( ctx );

                            ll.setOrientation(LinearLayout. HORIZONTAL );

                            ll.setGravity(Gravity. CENTER_VERTICAL );

                  

                            ImageView iv = new ImageView( ctx );

                            iv.setImageResource( drawableIDs [position]);

                            iv.setLayoutParams( new ViewGroup.LayoutParams(100, 40));
 
                            ll.addView(iv);                    

                  

                            TextView tv = new TextView( ctx );

                            tv.setText( stringIDs [position]);

                            tv.setTextSize(14);

                            tv.setTextColor(Color. BLUE );

                            ll.addView(tv);

                  

                            return ll;

                   }

}

 

 

         Activity 对应的代码改写如下:

public class ControlSpinner extends Activity

{

    private Spinner spinner ;

   

               private int [] drawableIDs = {

                        R.drawable. au ,

               R.drawable. ch ,

                        R.drawable. cn ,

                        R.drawable. us

               };

    private int [] nameIDs = {

                        R.string. au ,

                        R.string. ch ,

               R.string. cn ,

                        R.string. us

               };

                  

    @Override

    public void onCreate(Bundle savedInstanceState)

         {

        super .onCreate(savedInstanceState);

                  setContentView(R.layout. main );

 

               CustomizedAdapter customizedAdapter = new CustomizedAdapter( this , drawableIDs , nameIDs );
 
               spinner = (Spinner) this .findViewById(R.id. Spinner01 );

            spinner .setAdapter(customizedAdapter);

            spinner .setPrompt( " 请选择国家 : " );

        }

         … …

       }

         所得到的效果,和前面的情况是一样的。

 

        

用法 6 :获取所选项目的文本内容

1.     正常情况下 ( 用法 1~ 用法 4 所示的情形 ) ,我们可以通过这样的方式,来获取 Spinner 对象中所选项目的文本内容:

TextView tx_spinner = (TextView) spinner .getSelectedView();

String str = (String) tx_spinner.getText();

Toast.makeText ( this , str, Toast. LENGTH_LONG ).show();

 

2.     但是如果我们使用用法 5 中自定义的 Adapter ,就需要做一些稍微的改变,才能正常得到 Spinner 所选项目的文字内容。因为, CustomizedAdapter 中的 getView 方法,最后返回的是一个 LinearLayout 对象 (LinearLayout 继承了 View) ,而在 LinearLayout 对象中,又包含了一个 ImageView 和一个 TextView 。所以,
 
TextView tx_spinner = (TextView)spinner .getSelectedView();

这句话就不再使用了。因为 spinner.getSelectView() 会返回一个包含了一个 ImageView 和一个 TextView 的 LinearLayout 对象,而不再是一个单纯的 TextView 了。
 
 

         为此,我们在布局文件 main.xml 中,增加一个 Button ,因为我们想在点击一个按钮的情况下,获取 Spinner 中所选中的文字内
 
容。如下:

         < Button

                   android:id = "@+id/Button01"

                   android:layout_width = "120px"

                   android:layout_height = "60px"

                   android:text = "OK"

         />

        

         用法 5 中的 CustomizedAdapter 中的 getView 方法要增加一行代码 ( 粗体字 ) ,修改后如下

         public View getView( int position, View convertView, ViewGroup parent)

         {

                   // TODO Auto-generated method stub

                   LinearLayout ll = new LinearLayout( ctx );

                   ll.setOrientation(LinearLayout. HORIZONTAL );

                   ll.setGravity(Gravity. CENTER_VERTICAL );

                  

                   ImageView iv = new ImageView( ctx );

                   iv.setImageResource( drawableIDs [position]);

                   iv.setLayoutParams( new ViewGroup.LayoutParams(100, 40));

                   ll.addView(iv);                    

                  

                   TextView tv = new TextView( ctx );

                   tv.setText( stringIDs [position]);

                   tv.setTextSize(14);

                   tv.setTextColor(Color. BLUE );

                   tv.setTag( "tagTextView" );                 // 为 TextView 对象增加一个 Tag , 以便在后续的处理中 , 可以通过
 
                   ll.addView(tv);                                        // findViewWithTag 方法来获取这个 TextView 对象
 
                  

                   return ll;

         }

 

 

         修改 Activity 所对应的代码,使之如下:

         public class ControlSpinner extends Activity

implements

OnClickListener

{

               private Spinner spinner ;

               … …

                  

    @Override

               public void onCreate(Bundle savedInstanceState)

               {

                    super .onCreate(savedInstanceState);

           setContentView(R.layout. main );

 

                    CustomizedAdapter customizedAdapter = new CustomizedAdapter( this , drawableIDs , nameIDs );
 
                    spinner = (Spinner) this .findViewById(R.id. Spinner01 );

                    spinner .setAdapter(customizedAdapter);

                    spinner .setPrompt( " 请选择国家 : " );

 

                    // 获取按钮对象并为之增加监听器 :

                    Button button = (Button) this .findViewById(R.id. Button01 );
 
                    button.setOnClickListener( this );

               }

 

                  public void onClick(View v)

                  {

                            // TODO Auto-generated method stub

                    if (v.getId() == R.id. Button01 )

                    {

                                     // 方法 1~ 方法 4 的情形,可以使用如下被注释的的代码:

// TextView tx_spinner = (TextView)spinner.getSelectedView();

// String str = (String) tx_spinner.getText();

// Toast.makeText(this, str, Toast.LENGTH_LONG).show();

 

// 方法 5 所列的情形,需用如下方式获得 Spinner 所选中项目的文字内容

                              LinearLayout ll = (LinearLayout) spinner .getSelectedView();
 
                              TextView tv = (TextView)ll.findViewWithTag( "tagTextView" );         // 得到相应的 TextView 对象
 
                              String str = (String)tv.getText();

                              Toast.makeText ( this , str, Toast. LENGTH_LONG ).show();
 
                    }

                  }

                   … …

         }

         其他代码和用法 5 中的代码一致。运行结果:


 

可见可以正确地获得Spinner所选项目中的文字内容。

用法 7 :在 onItemSelected 方法中,获取所选项目的文本内容。

1.     首先让 Activity 实现 OnItemSelectedListener 接口

2.     给 spinner 对象增加 OnItemSelectedListener

3.     实现 OnItemSelectedListener 接口中定义的两个接口方法 onItemSelected 和 onNothingSelected

代码如下:

public class ControlSpinner extends Activity

implements

OnClickListener, OnItemSelectedListener

{

               private Spinner spinner ;

                  … …

               @Override

               public void onCreate(Bundle savedInstanceState)

               {

                    super .onCreate(savedInstanceState);

                    setContentView(R.layout. main );

 

                    CustomizedAdapter customizedAdapter = new CustomizedAdapter( this , drawableIDs , nameIDs );
 
                    spinner = (Spinner) this .findViewById(R.id. Spinner01 );

                    spinner .setAdapter(customizedAdapter);

                    spinner .setPrompt( " 请选择国家 : " );

 

                    // 获取按钮对象并为之设定 listener :

                    Button button = (Button) this .findViewById(R.id. Button01 );
 
                    button.setOnClickListener( this );

       

                    // 为 spinner 设定 listener :

                    spinner .setOnItemSelectedListener( this );

               } 

   

               public void onItemSelected(AdapterView<?> parent, View view, int position, long id)

               {

                            // 以下代码,适用于用法 1~4 中的情形

                            // if(parent.getId() == R.id.Spinner01)

                            // {

                            //      Toast.makeText(this, ((TextView)view).getText(), Toast.LENGTH_LONG).show();//tv.getText();
 
                            // }

                  

                            if (parent.getId() == R.id. Spinner01 )

                            {

                                      LinearLayout ll = (LinearLayout)view;

                                      TextView tv = (TextView)ll.findViewWithTag( "tagTextView" );

                             String str = (String)tv.getText();

                             Toast.makeText ( this , str, Toast. LENGTH_LONG ).show();

                            }                                                                                                                                                                             

               }

                                                        

                  public void onNothingSelected(AdapterView<?> parent)

                  {

                  }

                   … …

}

         其他代码与用法 6 同。

 

其中, onItemSelected 方法解释如下:

public abstract void onItemSelected (AdapterView <?> parent, View view, int position, long id)
 
Callback method to be invoked when an item in this view has been selected. Impelmenters can call getItemAtPosition(position) if they need to access the data associated with the selected item.
 
 

Parameters

         parent               The AdapterView where the selection happened

view                  The view within the AdapterView that was clicked

position            The position of the view in the adapter

id                        The row id of the item that is selected

 

posted on 2012-09-03 10:25  freeliver54  阅读(34711)  评论(1编辑  收藏  举报

导航