Search code examples
androidandroid-actionbar

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


I would like to change the style of the Up action button. It currently looks like this:

enter image description here

After much exploration on stack overflow and the Android documentation, I have seen examples where the Up action button icon can be swapped for a custom icon, like so:

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

This, however, is not what I'm looking for. I would like to replace the Up action button's icon with text, such as the button on the right side of the above screenshot.

Is there a way (from the java side) for me to replace this arrow icon with text that says "Cancel" without modifying or creating any drawable resources or layout files?


Solution

  • You cannot do that without a custom action bar layout in Android. In order to set a custom action bar, you need to do the following.

    <?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>
    

    And set the layout in your action bar from your activity like the following.

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

    Hope that helps!