質問

I want to add an action to the action bar, but it appears in my action bar as a drop down list. How can I add button to the action bar? My code is:

<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_search"
      android:icon="@drawable/ic_action_search"
      android:title="Add"
      showAsAction="ifRoom"/>
</menu>

  @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}
役に立ちましたか?

解決

If you are using android.app.Activity simply change showAsAction="always" to "android:showAsAction="always".

If you are using android.support.v7.app.Activity change the code as follows:

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

    <item android:id="@+id/action_search"
        android:icon="@drawable/ic_action_search"
        android:title="Add"
        app:showAsAction="ifRoom"/>
</menu>

他のヒント

You just simply add the one more item into menu and inflate that menu into your activity .... like below you will add your button and access that button into your activity...

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

        <item
            android:id="@+id/refresh"
            android:icon="@android:drawable/stat_notify_sync"
            showAsAction="ifRoom"/>
        <item
            android:id="@+id/action_bar_button_cancel"
            android:focusableInTouchMode="true"
            android:icon="@android:drawable/ic_menu_close_clear_cancel"
            showAsAction="ifRoom"/>

    </menu>

Inflating the menu like below.....

  @Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

Accessing method in action bar item is....

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.refresh:  
                          //logic       
            return true;
                case R.id.action_bar_button_cancel:
                          //logic       
                       return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }

that's if you have any doubt comment

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top