Add a button to the top right of action bar

十年热恋 提交于 2019-12-02 22:22:05
Android

You can add a button by editing/create the menu xml file:

<?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_name"
        android:icon="@drawable/you_resource_here"
        android:title="Text to be seen by user"
        app:showAsAction="always"
        android:orderInCategory="0"/>

</menu>

Then in your activity, if you created a new file your need to edit onCreateOptionsMenu

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

and you can edit what the actions do in the following method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_name) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
Arpit todewale

This might be easier, however I use a toolbar instead:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_name:
            //your code
            break;
    }
    return super.onOptionsItemSelected(item);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!