Onhar Onhar - 6 months ago 24
Android Question

Add buttons to the Activity Bar

I would like to know , how to add custom buttons to the activitybar and set OnClick method to it? If someone know the answer, can he/she please post it to me...

Like this:

enter image description here

Answer

you should create a menu xml resource, like this (let's call it example_menu.xml):

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

    <item
        android:id="@+id/action_one"
        android:icon="@drawable/one"
        android:title="actione one"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_two"
        android:icon="@drawable/two"
        android:title="actione two"
        app:showAsAction="ifRoom" />

</menu>

then in your activity, add this:

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.example_menu, menu);
    return true;
}

if you want your items to always be visible as icons, just change app:showAsAction="ifRoom" to app:showAsAction="always"