繁体   English   中英

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

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

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

在此处输入图片说明

在对堆栈溢出和Android文档进行了大量研究之后,我看到了一些示例,其中可以将“向上操作”按钮图标交换为自定义图标,如下所示:

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

但是,这不是我想要的。 我想用文本替换“向上操作”按钮的图标,例如上面的屏幕截图右侧的按钮。

有没有一种方法(从Java方面),我可以不用修改或创建任何可绘制的资源或布局文件,而用表示“取消”的文本替换此箭头图标?

没有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>

并按照以下操作在操作栏中设置布局。

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

希望有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM