在操作栏的右上角添加一个按钮

Bre*_*uro 21 android android-button android-actionbar

有没有办法可以在我的右上角添加一个按钮ActionBar,比如默认设置Button在哪里?我删除了设置,Button但我想在其中添加自定义Button.

And*_*oid 62

您可以通过编辑/创建菜单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_name"
        android:icon="@drawable/you_resource_here"
        android:title="Text to be seen by user"
        app:showAsAction="always"
        android:orderInCategory="0"/>

</menu>
Run Code Online (Sandbox Code Playgroud)

然后在您的活动中,如果您创建了一个需要编辑的新文件 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;
}
Run Code Online (Sandbox Code Playgroud)

并且您可以在以下方法中编辑操作的操作:

@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);
}
Run Code Online (Sandbox Code Playgroud)