AdapterView of UI components and its sub-class (3) details of the Spinner Control

Source: Internet
Author: User

AdapterView of UI components and its sub-class (3) details of the Spinner Control

The Spinner allows you to quickly select a value from a dataset. By default, the Spinner displays the selected value,Click the Spinner to bring up a dropdown menu or a dialog box containing all optional values. From this menu, you can select a new value for the Spinner.

I will discuss in this article

1. Basic usage of Spinner

2. xml attributes of the Spinner

3. Set the antries attribute, arrayadapter, and custom BaseAdapter of the Spinner)

The simplest Sipnner usage is to use the arrays array resource directly using the android: antries attribute of the spinner to display a drop-down list.

<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">    <!--{cke_protected}{C}%3C!%2D%2D%20%E8%BF%99%E4%B8%AAspinner%E7%94%B1entries%E6%8F%90%E4%BE%9B%E5%80%BC%20%2D%2D%3E-->    <spinner android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_height="wrap_content" android:dropdownwidth="200dp" android:entries="@array/province" android:prompt="@string/promp"></spinner></linearlayout>
Android: entries = "@ array/province" indicates that the data set of the Spinner is obtained from the resource array province. The province array resource is defined in values/arrays. xml:
<! -- {Cke_protected} {C} % 3C! % 2D % 2D % 3 Fxml % 20 version % 3D % 221.0% 20 encoding % 3D % 22utf-8% 22% 3F % 2D % 2D % 3E --> <resources> <string-array name = "province"> <item> Hunan province </item> <item> Hubei province </item> <item> Beijing </item> <item> Shanghai </item> </string -array> </resources>


 

Of course, in general, we need to respond to the events selected by the Spinner, which can be implemented through the OnItemSelectedListener callback method.

Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); Spinner spinner = (Spinner) findViewById (R. id. spinner1); spinner. setOnItemSelectedListener (new OnItemSelectedListener () {@ Override public void onItemSelected (AdapterView parent, View view, int pos, long id) {String [] ages = getResources (). getStringArray (R. array. ages); Toast. makeText (MainActivity. this, "you clicked:" + province [pos], 2000 ). show () ;}@ Override public void onNothingSelected (AdapterView parent) {// Another interface callback }});}}
2. xml attributes of the Spinner

,

Android: entries: bind the data source directly to the xml layout file (you can dynamically bind the data source in the Activity without setting it)

Android: prompt: the title of the selection dialog box (android: prompt = "travel to the West") displayed in the Spinner:

Android: spinnerMode: Display format of the Spinner. The value can only be "dialog" or "dropdown". The dialog box and drop-down list are displayed.

Android: dropDownHorizontalOffset (setDropDownHorizontalOffset (int): spinnerMode = "dropdown", the offset of the drop-down project selection window in the horizontal direction relative to the Spinner window

Android: dropDownVerticalOffset (setDropDownVerticalOffset (int): spinnerMode = "dropdown", the vertical offset of the drop-down project selection window relative to the Spinner window. You can also reference a resource (Format: @ [package:] type: name) or a topic attribute that contains this type of value.

Android: dropDownSelector: used to set the Display Effect of the List selector when spinnerMode = "dropdown. It can reference other resources in the format of "@ [+] [package]: type: name" or "? The format of [package:] [type:] name is used to apply the topic attribute, it is also a color value in the format of "# rgb", "# argb", "# rrggbb", and "aarrggbb ".

Android: dropDownWidth: Set the width of the drop-down box when spinnerMode = "dropdown.

This attribute can be a floating point size value with a unit, for example, 14.5sp. Valid units include: px (pixels), dp (density-independent pixels), sp (pixels scaled based on the size of the referenced font), in (INCHES), mm (millimeters)

It can also be one of the following constants:
Fill_parent =-1. The width of the drop-down box should be set using the screen width. This constant is discarded from API Level 8 and replaced by the mach_parent constant.
Mach_parent =-1. The width of the drop-down box should be set using the screen width. It is introduced in API Level 8.
Wrap_content =-2. The width of the drop-down box should be consistent with its content.

Android: gravity: This attribute is used to set the alignment of the selected project.

Android: popupBackground: This attribute is used to set the background of the drop-down list when "spinner =" dropdown. You can use the "@ [+] [package:] type: name" format to reference another resource or use "? In the format of [package:] [type:] name, topic attributes are used, you can also use color values in the format of "# rgb", "# argb", "# rrggbb", and "# aarrggbb.

 

3. Arrayadapter sets the Spinner's adapter and provides list items.

The following two Spinner lists are provided. The first is the "drop-down list", the android: entries attribute provides an array, and the second is the "dialog" format. The ArrayAdapter provides an adapter.

Main. xml

<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">    <!--{cke_protected}{C}%3C!%2D%2D%20%E8%BF%99%E4%B8%AAspinner%E7%94%B1entries%E6%8F%90%E4%BE%9B%E5%80%BC%20%2D%2D%3E-->    <spinner android:id="@+id/spinner1" android:layout_width="match_parent" android:layout_height="wrap_content" android:dropdownwidth="200dp" android:entries="@array/province"><!--{cke_protected}{C}%3C!%2D%2D%20%E8%BF%99%E4%B8%AASpinner%E6%9C%89adapter%E6%8F%90%E4%BE%9B%E5%80%BC%20%EF%BC%8Candroid%3AspinnerMode%3D%22dialog%22%E4%B8%8B%E6%8B%89%E5%88%97%E8%A1%A8%E6%98%AF%E4%BB%A5%E5%AF%B9%E8%AF%9D%E6%A1%86%E7%9A%84%E5%BD%A2%E5%BC%8F%2D%2D%3E-->    <spinner android:id="@+id/spinner2" android:layout_width="match_parent" android:layout_height="wrap_content" android:popupbackground="#f00" android:spinnermode="dialog" android:prompt="@string/promp"></spinner></spinner></linearlayout>
MainActivity. java
Public class MainActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // obtain the spinner component in the layout file of the Spinner. id. spinner2); String [] arr = {"Tang Seng", "Sun Wukong", "", "Sha Monk"}; // create the ArrayAdapter object
 
  
Aa = new ArrayAdapter
  
   
(This, android. R. layout. simple_list_item_1, arr); sp. setAdapter (aa );}
  
 


This is the standard usage method of the Spinner. Two lines of code determine the appearance of the Spinner:
 ArrayAdapter
 
   aa=new ArrayAdapter
  
   (this,android.R.layout.simple_list_item_1,arr);
  
 
The second parameter is the default Spinner style when the menu is not expanded. android. R. layout. simple_spinner_item is the built-in layout of the system.

4. Create a Spinner using a custom Adapter

This situation is suitable for complicated cases such as with icons.
The following defines a Spinner for selecting a contact.

Main. xml

 <linearlayout android:layout_width="fill_parent" android:layout_height="80dip" android:orientation="vertical">              <spinner android:id="@+id/spinner2" android:layout_width="wrap_content" android:layout_height="wrap_content">    </spinner></linearlayout>
Person. java
package com.example.spinnerdemo;  public class Person {    private String personName;    private String personAddress;    public Person(String personName, String personAddress) {        super();        this.personName = personName;        this.personAddress = personAddress;    }    public String getPersonName() {        return personName;    }    public void setPersonName(String personName) {        this.personName = personName;    }    public String getPersonAddress() {        return personAddress;    }    public void setPersonAddress(String personAddress) {        this.personAddress = personAddress;    }  }

Custom MyAdapter. java

Package com. example. spinnerdemo; import java. util. list; import android. content. context; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widget. baseAdapter; import android. widget. imageView; import android. widget. textView;/*** custom adapter class * @ author jiangqq **/public class MyAdapter extends BaseAdapter {private List
 
  
MList; private Context mContext; public MyAdapter (Context pContext, List
  
   
PList) {this. mContext = pContext; this. mList = pList;} @ Override public int getCount () {return mList. size () ;}@ Override public Object getItem (int position) {return mList. get (position) ;}@ Override public long getItemId (int position) {return position ;}/ *** the following code is important. The layout of each item is two text boxes, of course you can also add other components, which is very rich */@ Override public View getView (int position, View convertView, ViewGroup parent) {LayoutInfla Ter _ LayoutInflater = LayoutInflater. from (mContext); convertView = _ LayoutInflater. inflate (R. layout. item_custom, null); if (convertView! = Null) {ImageView imageView = (ImageView) convertView. findViewById (R. id. image); imageView. setImageResource (R. drawable. ic_launcher); TextView _ TextView1 = (TextView) convertView. findViewById (R. id. textView1); TextView _ TextView2 = (TextView) convertView. findViewById (R. id. textView2); _ TextView1.setText (mList. get (position ). getPersonName (); _ TextView2.setText (mList. get (position ). getPersonAddress ();} return convertView ;}}
  
 
MainActivity. java
// Initialize the control Spinner spinner2 = (Spinner) findViewById (R. id. spinner2); // create a data source List
 
  
Persons = new ArrayList
  
   
(); Persons. add (new Person ("Zhang San", "Shanghai"); persons. add (new Person ("Li Si", "Shanghai"); persons. add (new Person ("Wang Wu", "Beijing"); persons. add (new Person ("Zhao ", "Guangzhou"); // create an Adapter to bind the data source MyAdapter _ MyAdapter = new MyAdapter (this, persons ); // bind the Adapter spinner2.setAdapter (_ MyAdapter );
  
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.