Spinner in ActionBar doesn't appear

2019-06-07 02:08发布

I've implemeted spinner like here . And now I want to place spinner in ActionBar (setting spinner as CustomView to actionBar) but it doesn't appear there :(

Spinner spinner = (Spinner) findViewById(R.id.planets_spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.planets_array, android.R.layout.simple_spinner_item);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 

        spinner.setAdapter(adapter);

        actionBar.setCustomView(spinner);

and here is .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:baselineAligned="false"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@+id/parkfragment"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <Spinner
        android:id="@+id/planets_spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Please, don't suggest to use ActionBar DropDown List, I can't use it because I'm already using ActionBar Tabs. android doesn't allow to use them both at the same time. Any help will be appreciated

1条回答
欢心
2楼-- · 2019-06-07 02:15

Your code is missing this line:

actionBar.setDisplayShowCustomEnabled(true); 

See ActionBar#setDisplayShowCustomEnabled(boolean showCustom) for reference.


Update:

Why is there an empty FrameLayout in your layout that occupies all the width and height? Remove it. And remove the LinearLayout, too. Just use this as the layout:

<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/planets_spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" /> 

And then write something like this and everything is fine:

actionBar.setCustomView(R.layout.your_layout_with_the_spinner);
actionBar.setDisplayShowCustomEnabled(true);

Spinner spinner = (Spinner) findViewById(R.id.planets_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.planets_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
查看更多
登录 后发表回答