簡體   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