如何将向上操作图标更改为带有文本 Android 的按钮?

How do I change the up action icon into button with text on Android?

我想更改向上操作按钮的样式。目前看起来像这样:

在对堆栈溢出和 Android 文档进行了大量探索之后,我看到了可以将向上操作按钮图标替换为自定义图标的示例,如下所示:

getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_yourindicator);

然而,这不是我要找的。我想把Up action按钮的图标换成文字,比如上面截图右边的按钮。

有没有办法(从 java 方面)让我用 "Cancel" 的文字替换这个箭头图标,而无需修改或创建任何可绘制资源或布局文件?

如果 Android 中没有自定义操作栏布局,您将无法做到这一点。为了设置自定义操作栏,您需要执行以下操作。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="64dp"
    android:background="@android:color/white">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/cancel_button"
        android:text="Contact"
        android:textColor="@android:color/black"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/cancel_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_margin="16dp"
        android:text="Cancel"
        android:textColor="@android:color/black" />
</RelativeLayout>

然后从您的 activity 中设置操作栏中的布局,如下所示。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActionBar mActionBar = getSupportActionBar();
    mActionBar.setDisplayShowHomeEnabled(false);
    mActionBar.setDisplayShowTitleEnabled(false);
    LayoutInflater mInflater = LayoutInflater.from(this);

    View mCustomView = mInflater.inflate(R.layout.custom_action_bar_layout, null);
    TextView cancelButton = (TextView) mCustomView.findViewById(R.id.cancel_button);
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finish();
        }
    });

    mActionBar.setCustomView(mCustomView);
    mActionBar.setDisplayShowCustomEnabled(true);
}

希望对您有所帮助!