Get reference to a Spinner in ActionBar

2020-07-27 05:49发布

问题:

findViewById() works fine when you need to find something any UI element that is in your layout. However, using the second option of this answer How to add a Dropdown item on the action bar, I added a Spinner to my ActionBar.

Now the problem I am facing is how to retrieve a reference to this Spinner so that I can change the font that it uses. How do I do that?

My menu/sort_spinner looks like this:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/sort" 
        android:showAsAction="always"
        android:title="@string/sort"
        android:actionLayout="@layout/actionbar_spinner"/>
</menu>  

and layout/actionbar_spinner like this:

<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:spinnerMode="dropdown"
    android:id="@+id/spinner"
    android:entries="@array/type" />

回答1:

You have to do it in the public boolean onCreateOptionsMenu(Menu menu).

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.sort_spinner, menu);
    MenuItem spinnerItem = menu.findItem(R.id.sort);
    Spinner spinner = (Spinner)spinnerItem.getActionView().findViewById(R.id.spinner);
    //Your rest of code...
    return super.onCreateOptionsMenu(menu);
}


回答2:

Inside of your onCreateOptionsMenu you can save a global reference of your menu like this:

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.actionbar_items, menu);
    mMenu = menu;
    ...
}

EDIT:

To change the Font you will however have to use an adapter. Here's an example that should work.

MenuItem item = mMenu.findItem(R.id.sort);
Spinner spinner = (Spinner) item.getActionView().findViewById(R.id.spinner);

MyAdapter adapter = new MyAdapter(this, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spinner.setAdapter(adapter);

private class MyAdapter extends ArrayAdapter {

    public MyAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    public TextView getView(int position, View convertView, ViewGroup parent) {
        TextView v = (TextView) super.getView(position, convertView, parent);
        v.setTypeface(myFont);
        return v;
    }

    public TextView getDropDownView(int position, View convertView, ViewGroup parent) {
        TextView v = (TextView) super.getView(position, convertView, parent);
        v.setTypeface(myFont);
        return v;
    }

}