Monday, September 21, 2015

android - How to change ActionBar title programmatically

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#f9fff5"
    >
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change ActionBar Title Text"
        android:layout_marginTop="10dp"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.app.ActionBar;


public class MainActivity extends Activity {


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

        // Get the widgets reference from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final Button btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Get the ActionBar
                /*
                    public ActionBar getActionBar ()
                        Retrieve a reference to this activity's ActionBar.

                    Returns
                        The Activity's ActionBar, or null if it does not have one.
                */
                ActionBar ab = getActionBar();

                // Change the ActionBar title text
                /*
                    public abstract void setTitle (CharSequence title)
                        Set the action bar's title. This will only be
                        displayed if DISPLAY_SHOW_TITLE is set.
                */
                ab.setTitle("This is new text for ActionBar title");
            }
        });
    }
}
More android examples