Search code examples
javaandroidspinnerandroid-actionbar-compat

Spinner inside ActionBarCompact


I am beginner to android Development, so please don't be hard on me..

I am trying to use ActionBarCompact so that ActionBar can be compatible upto API level 8. I want a spinner in it which can help me in navigating activities. So my Question is that how can I have it? Do I need to set some flag or add to actionbar? I couldn't find any such example which suits my need.

What I have tried is:

Menu.m

public class menu extends ActionBarActivity {

    ActionBar actionbar;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menutab);

        actionbar = getSupportActionBar();
        actionbar.setTitle("Menu");
        actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

//Now what should I do further?
    }
}

Menu.xml

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

  <TextView android:text="menu tab!"
            android:padding="15dip"
            android:textSize="18sp"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/> 
</LinearLayout>

Edit To @Szymon's Question in comment

Custom layout I designed for spinner:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/simpleText"
    android:singleLine="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ellipsize="marquee" />

Using above as:

ArrayAdapter<CharSequence> mSpinnerAdapter = ArrayAdapter.createFromResource(this,R.array.menu_items, R.id.simpleText);
actionbar.setListNavigationCallbacks(mSpinnerAdapter, this);

There will be many things I am doing wrong. Please help me to correct them or point me towards good example... Thanks alot.


Solution

  • 1) You need to also create an adapter:

    ArrayAdapter<CharSequence> mSpinnerAdapter =  
                ArrayAdapter.createFromResource(this, R.array.verbTypes,
                android.R.layout.simple_spinner_dropdown_item);
    actionBar.setListNavigationCallbacks(mSpinnerAdapter, this);
    

    2) and overrride onNavigationItemSelected

    @Override
    public boolean onNavigationItemSelected(int arg0, long arg1) {
    
        switch (arg0) {
        case 0: // your code
        case 1: // your code
        }
    
        return true;
    }
    

    3) You don't need to declare anything in your menu xml.

    4) But to use a simple spinner adapter like I did, you should declare your strings:

    <string-array name="verbTypes">
        <item>All</item>
        <item>Irregular</item>
        <item>Regular</item>
    </string-array>