Android Development Tip 6--Spinner

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/crazy1235/article/details/70903974

Set Spinner Text Center

By default, the effect of the spinner control is this:

What do I do if I want to center text???

Set in the layout file

android:gravity="center"

It doesn't work!!

Source of the daytime

First look at the Spinner constructor

 Public Spinner(context context, AttributeSet attrs,intDefstyleattr,intDefstyleres,intmode, Theme popuptheme) {Super(Context, Attrs, defstyleattr, defstyleres);FinalTypedArray a = Context.obtainstyledattributes (Attrs, R.styleable.spinner, defstyleattr, defstyleres);//Omit code        if(mode = = Mode_theme)        {mode = A.getint (R.styleable.spinner_spinnermode, Mode_dialog); }//Judging pop-up mode dialog or dropdown        Switch(mode) { CaseMode_dialog: {mpopup =NewDialogpopup ();//DialogpopupMpopup.setprompttext (a.getstring (r.styleable.spinner_prompt)); Break; } CaseMode_dropdown: {FinalDropdownpopup popup =NewDropdownpopup (Mpopupcontext, Attrs, defstyleattr, defstyleres);//Dropdownpopup                //Omit code                 Break; }        }// ...A.recycle ();//Set adapter        if(Mtempadapter! =NULL) {Setadapter (mtempadapter); Mtempadapter =NULL; }    }

When Mtempadapter is not empty, the Setadapter () setting adapter is called!

But if we set the entries property in XML, we don't set the adapter

android:entries="@array/date_spinner_items"

How did the list come out?!

Look at the parent class ~ ~

Absspinner

 Public Absspinner(context context, AttributeSet attrs,intDefstyleattr,intDefstyleres) {Super(Context, Attrs, defstyleattr, defstyleres); Initabsspinner ();FinalTypedArray a = Context.obtainstyledattributes (Attrs, R.styleable.absspinner, defstyleattr, defstyleres);Finalcharsequence[] entries = A.gettextarray (r.styleable.absspinner_entries);if(Entries! =NULL) {Finalarrayadapter<charsequence> adapter =NewArrayadapter<charsequence> (context, r.layout.simple_spinner_item, entries);            Adapter.setdropdownviewresource (R.layout.simple_spinner_dropdown_item);        Setadapter (adapter);    } a.recycle (); }

As seen from the constructor function, when the entries property is not empty, the setadapter () function is called!

Note here that the Arrayadapter adapter is used. There are also two important layout files:

    • Simple_spinner_item

    • Simple_spinner_dropdown_item

Subclass Spinner Overrides the Setadapter function

@Override    public void setAdapter(SpinnerAdapter adapter) {        ...         super.setAdapter(adapter);        ...        mPopup.setAdapter(new DropDownAdapter(adapter, popupContext.getTheme()));    }

Mpopup is an interface object that encapsulates the setup adapter, display list, close list, and so on!

Whether the spinner is a dialog form or a dropdown form , the interface is implemented!

privateclass DialogPopup implements SpinnerPopup, DialogInterface.OnClickListener
privateclass DropdownPopup extends ListPopupWindow implements SpinnerPopup

OK, now look at dropdownadapter .

Private Static  class dropdownadapter implements listadapter, spinneradapter {         PrivateSpinneradapter Madapter;PrivateListAdapter Mlistadapter; Public Dropdownadapter(@Nullable spinneradapter Adapter, @Nullable resources.theme dropdowntheme) {Madapter = adapter;//NOTE here!!!             //omit generation?} Public int GetCount() {returnMadapter = =NULL?0: Madapter.getcount (); } PublicObjectGetItem(intPosition) {returnMadapter = =NULL?NULL: Madapter.getitem (position); } Public Long Getitemid(intPosition) {returnMadapter = =NULL? -1: Madapter.getitemid (position); } PublicViewGetView(intPosition, View Convertview, ViewGroup parent) {returnGetdropdownview (position, convertview, parent); } PublicViewGetdropdownview(intPosition, View Convertview, ViewGroup parent) {return(Madapter = =NULL) ?NULL: Madapter.getdropdownview (position, convertview, parent); }//omit generation?}

Pop out the list of each item's view rendering through the getdropdownview function!

and Madapter is passed through the constructor function!

Come back here:

mPopup.setAdapter(new DropDownAdapter(adapter, popupContext.getTheme()));

At this point adapter is the arrayadapter of the spinner parent class Absspinner constructor.

Then look at the Getdropdownview function in the Arrayadapter class.

@Override    publicgetDropDownView(int position, @Nullable View convertView,            @NonNull ViewGroup parent) {        finalnull ? mInflater : mDropDownInflater;        return createViewFromResource(inflater, position, convertView, parent, mDropDownResource);    }
Private @NonNullView Createviewfromresource (@NonNullLayoutinflater Inflater,intPosition@NullableView Convertview,@NonNullViewGroup Parent,intResource) {FinalView view;FinalTextView text;if(Convertview = =NULL{view = Inflater.inflate (resource, parent,false); }Else{view = Convertview; }Try{if(Mfieldid = =0{text = (TextView) view; }Else{text = (TextView) View.findviewbyid (Mfieldid);if(Text = =NULL) {Throw NewRuntimeException ("Failed to find View with ID"+ mcontext.getresources (). Getresourcename (Mfieldid) +"in Item Layout"); }            }        }Catch(ClassCastException e) {LOG.E ("Arrayadapter","must supply a resource ID for a TextView");Throw NewIllegalStateException ("Arrayadapter requires the resource ID to be a TextView", e); }//Omit code!!!         returnView }

Source see here can be found, by mapping mdropdownresource This layout file, to get spinner list of the item layout!

And, this layout file is set exactly in the Absspinner constructor

adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);

So, now want to change the spinner Text Center display! You need to set the appropriate adapter!

Ok. Now, let's see this layout file.

< Checkedtextview  xmlns:android  = "HTTP +/ Schemas.android.com/apk/res/android " android:id  =     "@android: Id/text1"  style  = "Android:attr/spinnerdropdownitemstyle"  android:singleline  = "true"  android:layout_width  = "match_parent"  android:layout_height  =" android:attr/ Dropdownlistpreferreditemheight " android:ellipsize  =" marquee "/>   

You can see that the item layout file is just a checkedtextview

We now want to center the text of this list in the display!

The Gravity property of the trace style file Discovery setting is center_vertical

<itemname="android:gravity">center_vertical</item>

Now try to rewrite the layout file.

Simple_spinner_dropdown_item.xml

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@android:id/text1"    style="?android:attr/spinnerDropDownItemStyle"    android:layout_width="match_parent"    android:layout_height="?attr/listPreferredItemHeightSmall"    android:ellipsize="marquee"    android:gravity="center"// !!!    android:maxLines="1" />

Then set the adapter to the spinner object in activity!

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, dates);arrayAdapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);spinner.setAdapter(arrayAdapter);

After running, the discovery is not centered!

Now, look back at the mpopup.show () function that displays the list

Join us to choose the dropdown mode!

Dropdownpopup.show ()

public   void  show  (int  textdirection, int  textalignment) {final  b            Oolean  wasshowing = isshowing ();            Computecontentwidth ();            Setinputmethodmode (listpopupwindow.input_method_not_needed);            super . Show (); final             ListView ListView = Getlistview ();            Listview.setchoicemode (Listview.choice_mode_single);            Listview.settextdirection (textdirection);            Listview.settextalignment (textalignment); SetSelection (Spinner.            This . Getselecteditemposition ()); //... Omit code }  

As you can see, the pop-up View is a ListView

direction and textaligment Two properties are set for the ListView!!!

Android Development Tip 6--Spinner

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.