ActionBar Compat do not show dropdown menu

久未见 提交于 2019-12-04 20:47:57

To avoid this, we need use PopupMenu!

For example:

action_bar_buttons.xml

   <?xml version="1.0" encoding="utf-8"?>
    <menu   xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:mynamespace="http://schemas.android.com/apk/res-auto" >

        <item
            android:id="@+id/some_other_btn"
            android:icon="@drawable/some_other_btn"
            mynamespace:showAsAction="always"
            android:title="@string/some_other_btn"
            android:visible="true">
        </item>

        <item
            android:id="@+id/open_drop_down"
            android:icon="@drawable/open_drop_down"
            mynamespace:showAsAction="always"
            android:title="@string/open_drop_down"
            android:visible="true"/>

    </menu>

drop_down_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu   xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:mynamespace="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/item_1"
        android:title="@string/item_1"
        android:visible="true"
        mynamespace:showAsAction="always">
    </item>
    <item
        android:id="@+id/item_2"
        android:title="@string/item_1"
        android:visible="true"
        mynamespace:showAsAction="always">
    </item>

</menu>

in MainActivity.java

public void showPopup(int itemId){
        View view = findViewById(itemId);
        PopupMenu popupMenu = new PopupMenu(getSupportActionBar().getThemedContext(), view);
        popupMenu.setOnMenuItemClickListener(/* drop_down item click listener */);
        popupMenu.getMenuInflater().inflate(R.menu.drop_down_menu, popupMenu.getMenu());
        popupMenu.show();
    }


@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    /* . . . */ 

    case R.id.open_drop_down:
        showPopup(R.id.open_drop_down);
        break;

    /* . . . */ 

    default:
        break;
    }

    return super.onOptionsItemSelected(item);
}

You may want to use Sherlock Action Bar if your target devices are android SDK < 11.

Have a look at http://actionbarsherlock.com/

Github sample is here: https://github.com/JakeWharton/ActionBarSherlock-Gradle-Sample There is a example here: http://www.androidbegin.com/tutorial/implementing-actionbarsherlock-in-android/ Another example here: http://www.grokkingandroid.com/adding-actionbarsherlock-to-your-project/

If you do not want to use ActionBarSherlock, you have to use android support library, but I would recommend to use ActionBarSherlock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!