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

Add a button to the top right of action bar

有什么方法可以在 ActionBar 的右上角添加一个按钮,就像默认设置 Button 所在的位置一样?我删除了设置 Button,但我想在原处添加自定义 Button

您可以通过 editing/create 菜单 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>

然后在您的 activity 中,如果您创建了一个新文件,则需要编辑 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;
}

您可以通过以下方法编辑操作的作用:

@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);
}

这可能更容易,但我改用工具栏:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_name:
            //your code
            break;
    }
    return super.onOptionsItemSelected(item);
}