Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

android - Adding spinner to ActionBar (not Navigation

I have added a spinner to my ActionBar using the second option from the answer here .

How to I add a spinner adapter to the spinner? I tried using a Spinner object as Google describes here but get a null Spinner object.

Anybody know how to do this? I don't want the spinner to be in the navigation area of the action bar but in with the other action items (I am using the split action bar).

Thanks for the help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know this is an old question, but just in case someone stumbles on it (as I did) and still looks for a complete answer, here is how to do it using the compatibility library, so that it works from to v7 (Android 2.1 Eclair) to current v19 (Android 4.4 KitKat):

In menu_layout.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >

  <item android:id="@+id/spinner"
    yourapp:showAsAction="ifRoom"
    yourapp:actionViewClass="android.widget.Spinner" />
</menu>

Using http://schemas.android.com/apk/res-auto namespace aliased as yourapp enables you to use the attributes showAsAction and actionViewClass that do not exist on older versions of Android.

Then in your Activity code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_layout, menu);
    MenuItem item = menu.findItem(R.id.spinner);
    Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
    spinner.setAdapter(adapter); // set the adapter to provide layout of rows and content
    spinner.setOnItemSelectedListener(onItemSelectedListener); // set the listener, to perform actions based on item selection

Et voilà!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...