258

Currently it just displays the name of the application and I want it to display something custom and be different for each screen in my app.

For example: my home screen could say 'page1' in the action bar while another activity that the app switches to could have 'page2' in that screens action bar.

Tim
  • 41,901
  • 18
  • 127
  • 145
dootcher
  • 3,059
  • 4
  • 22
  • 18

20 Answers20

385

Update: Latest ActionBar (Title) pattern:

FYI, ActionBar was introduced in API Level 11. ActionBar is a window feature at the top of the Activity that may display the activity title, navigation modes, and other interactive items like search.

I exactly remember about customizing title bar and making it consistent through the application. So I can make a comparison with the earlier days and can list some of the advantages of using ActionBar:

  1. It offers your users a familiar interface across applications that the system gracefully adapts for different screen configurations.
  2. Developers don't need to write much code for displaying the Activity Title, icons and navigation modes because ActionBar is already ready with top level abstraction.

For example:

enter image description here

enter image description here

=> Normal way,

getActionBar().setTitle("Hello world App");   
getSupportActionBar().setTitle("Hello world App");  // provide compatibility to all the versions

=> Customizing Action Bar,

For example:

@Override
public void setActionBar(String heading) {
    // TODO Auto-generated method stub

    com.actionbarsherlock.app.ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(false);
    actionBar.setDisplayShowHomeEnabled(false);
    actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.title_bar_gray)));
    actionBar.setTitle(heading);
    actionBar.show();

}

Styling the Action Bar:

The ActionBar provides you with basic and familiar looks, navigation modes and other quick actions to perform. But that doesn't mean it looks the same in every app. You can customize it as per your UI and design requirements. You just have to define and write styles and themes.

Read more at: Styling the Action Bar

And if you want to generate styles for ActionBar then this Style Generator tool can help you out.

=================================================================================

Old: Earlier days:

=> Normal way,

you can Change the Title of each screen (i.e. Activity) by setting their Android:label

   <activity android:name=".Hello_World"
                  android:label="This is the Hello World Application">
   </activity>

=> Custom - Title - bar


But if you want to Customize title-bar in your own way, i.e. Want to put Image icon and custom-text, then the following code works for me:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

titlebar.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="400dp" 
  android:layout_height="fill_parent"
  android:orientation="horizontal">

<ImageView android:id="@+id/ImageView01" 
            android:layout_width="57dp" 
            android:layout_height="wrap_content"
            android:background="@drawable/icon1"/>

<TextView 

  android:id="@+id/myTitle" 
  android:text="This is my new title" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  android:textColor="@color/titletextcolor"
   />
</LinearLayout>

TitleBar.java

public class TitleBar extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final boolean customTitleSupported = 
                requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        if (customTitleSupported) {
            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
                R.layout.titlebar);
        }
        final TextView myTitleText = (TextView) findViewById(R.id.myTitle);
        if (myTitleText != null) {
            myTitleText.setText("NEW TITLE");
            // user can also set color using "Color" and then
            // "Color value constant"
            // myTitleText.setBackgroundColor(Color.GREEN);
        }
    }
}

strings.xml

The strings.xml file is defined under the values folder.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Set_Text_TitleBar!</string>
    <string name="app_name">Set_Text_TitleBar</string>
    <color name="titlebackgroundcolor">#3232CD</color>
    <color name="titletextcolor">#FFFF00</color>
</resources>
JDJ
  • 4,298
  • 3
  • 25
  • 44
Paresh Mayani
  • 127,700
  • 71
  • 241
  • 295
  • 2
    Follow this example to set Custom Title in android for an activity or globally for entire application : http://labs.makemachine.net/2010/03/custom-android-window-title/ – Paresh Mayani Aug 17 '10 at 06:15
  • 1
    +1 ! thanks for this, but could you tell why the android:layout_width="400px" , to the parent linear layout? – quinestor Dec 18 '12 at 13:16
  • 2
    @quinestor yes you can use "wrap_content" or "fill_parent" if you want, this is just for example. – Paresh Mayani Dec 18 '12 at 13:21
  • Some hints for javascript? – ivy Feb 06 '13 at 08:01
  • 1
    I would go against using "px" instead of independent units such as "dp" because a lot of new learners learn a lot more than just what was answered by trying to break down the code and get the most out of it. – Akshat Agarwal Nov 12 '13 at 21:28
  • @AkshatAgarwal changed 'px' values with 'dp'. Thanks for pointing out. – Paresh Mayani Nov 13 '13 at 04:59
  • better not use the old method on new apps... the style contains an action-bar by default and they cannot live together...(you can remove it...) – Dani Feb 17 '14 at 17:59
  • Yeah agree with you that ActionBar is there by default, but still I have kept it here in case anyone wants to use still :) – Paresh Mayani Feb 18 '14 at 03:22
  • yes this is great when you when you use version which older than API 11. – Kelum Deshapriya Mar 10 '14 at 10:45
  • @KelumDeshapriya answer contains both the things older and latest :) – Paresh Mayani Mar 10 '14 at 11:22
  • Works like wonder!! Thanks.@PareshMayani please, do you think you could help me with this question http://stackoverflow.com/questions/25598696/recommended-way-order-to-read-data-from-a-webservice-parse-that-data-and-inse – Axel Sep 01 '14 at 23:00
  • what's com.actionbarsherlock doing in this example? – axd Jul 26 '16 at 13:59
  • @axd dude see the answer posted and updated date. FYI, action bar has got a lot many updates since it's existence! – Paresh Mayani Jul 27 '16 at 04:26
  • I know... it's a problem with SO... these answer keep flooding the net, but have become obsolete... – axd Jul 29 '16 at 07:49
118

You can define the label for each activity in your manifest file.

A normal definition of a activity looks like this:

<activity
     android:name=".ui.myactivity"
     android:label="@string/Title Text" />

Where title text should be replaced by the id of a string resource for this activity.

You can also set the title text from code if you want to set it dynamically.

setTitle(address.getCity());

with this line the title is set to the city of a specific adress in the oncreate method of my activity.

Janusz
  • 187,060
  • 113
  • 301
  • 369
57

You can define your title programatically using setTitle within your Activity, this method can accept either a String or an ID defined in your values/strings.xml file. Example:

public class YourActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        setTitle(R.string.your_title);
        setContentView(R.layout.main);

    }
}
donturner
  • 17,867
  • 8
  • 59
  • 81
19

We can change the ActionBar title in one of two ways:

  1. In the Manifest: in the manifest file, set the label of each Activity.

    android:label="@string/TitleWhichYouWantToDisplay"
    
  2. In code: in code, call the setTitle() method with a String or the id of String as the argument.

    public class MainActivity extends Activity {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
    
            setTitle(R.string.TitleWhichYouWantToDisplay);
            // OR You can also use the line below
            // setTitle("MyTitle")
            setContentView(R.layout.activity_main);
    
        }
    }
    
JDJ
  • 4,298
  • 3
  • 25
  • 44
Radheshyam Singh
  • 479
  • 3
  • 10
19

Inside Activity.onCreate() callback or in the another place where you need to change title:

getSupportActionBar().setTitle("Whatever title");
Andrew
  • 36,676
  • 11
  • 141
  • 113
5

Kotlin

You can do it programmatically in Kotlin this way. You just ignore it if "supportActionBar" is null:

    supportActionBar?.setTitle(R.string.my_text)
    supportActionBar?.title = "My text"

Or this way. It throws an exception if "supportActionBar" is null.

    supportActionBar!!.setTitle(R.string.my_text)
    supportActionBar!!.title = "My text"
Mateus Nascimento
  • 815
  • 10
  • 11
  • 1
    The only real solution! This answer is not only up to date, but it also is using Kotlin. Thank you! – Akito Mar 27 '21 at 02:20
5

try do this...

public void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
    this.setTitle(String.format(your_format_string, your_personal_text_to_display));
    setContentView(R.layout.your_layout);
       ...
       ...
}

it works for me

nonickh
  • 229
  • 1
  • 3
  • 9
4

The below code worked well for me inside the OnCreate method:

getSupportActionBar().setTitle("Text to display");
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
3

Little bit older but had the same problem. I did it like this:

strings.xml

<string name="title_awesome_app">My Awesome App</string>

and make sure you set this in your AndroidManifest.xml:

<activity
            ...
            android:label="@string/title_awesome_app" >
            ...
</activity>

it's easy and you don't have to worry about null-references and other stuff.

Javatar
  • 2,518
  • 1
  • 31
  • 43
3
getActionBar().setTitle("edit your text"); 
3

The Easiest way to change the action bar name is to go to the AndroidManifest.xml and type this code.

<activity android:name=".MainActivity"
    android:label="Your Label> </activity>
3

You just add this code in the onCreate method.

setTitle("new title");
pushkin
  • 9,575
  • 15
  • 51
  • 95
Nech
  • 148
  • 5
2
ActionBar ab = getActionBar();
TextView tv = new TextView(getApplicationContext());

LayoutParams lp = new RelativeLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, // Width of TextView
        LayoutParams.WRAP_CONTENT);
tv.setLayoutParams(lp);
tv.setTextColor(Color.RED);
ab.setCustomView(tv);

For more information check this link :

http://android--code.blogspot.in/2015/09/android-how-to-change-actionbar-title_21.html

Gabriella Angelova
  • 2,985
  • 1
  • 17
  • 30
1

getSupportActionBar().setTitle("title");

Phani varma
  • 475
  • 5
  • 7
0

The easiest way is to call this.setTitle("...") if you are in the activity. And if you are in a fragment, just call getActivity().setTitle("...");

This way will let you change the title anytime, no need to call it before setContentView(R.layout.activity_test);

Zakaria Hossain
  • 2,188
  • 2
  • 13
  • 24
Hatim
  • 1,516
  • 1
  • 18
  • 30
0

The best way to change the action bar name is to go to the AndroidManifest.xml and type this code.

<activity android:name=".YourActivity"
        android:label="NameYouWantToDisplay> </activity>
0

For future developers that are using AndroidX and the navigation architectural component.

Instead of setting the toolbar title using one of the solutions above, which can be very painful if you want to set it dynamically on a back stack change, you can set a placeholder for the title of the fragment in the navigation graph like the following:

<fragment
    android:id="@+id/some_fragment"
    android:name="package.SomeFragment"
    android:label="Hello {placeholder}"
    tools:layout="@layout/fragment_some">
    <argument
        android:name="placeholder"
        app:argType="string" />
</fragment>

The placeholder value has to be provided using the FragmentDirections (via the action method).

It is then replaced in the title and show like Hello World (when placeholder = "World").

Fabian Damken
  • 1,477
  • 1
  • 15
  • 24
0

if u r using navigation bar to change fragment then u can add change it where u r changing Fragment like below example :

 public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.clientsidedrawer:
                    //    Toast.makeText(getApplicationContext(),"Client selected",Toast.LENGTH_SHORT).show();
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new clients_fragment()).commit();
                    break;
    
                case R.id.adddatasidedrawer:
                    getSupportActionBar().setTitle("Add Client");
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new addclient_fragment()).commit();
                    break;
    
                case R.id.editid:
                    getSupportActionBar().setTitle("Edit Clients");
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Editclient()).commit();
                    break;
    
                case R.id.taskid:
                    getSupportActionBar().setTitle("Task manager");
                    getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new Taskmanager()).commit();
                    break;

if u r using simple activity then just call :

getSupportActionBar().setTitle("Contact Us");

to change actionbar/toolbar color in activity use :

getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#06023b")));

to set gradient to actionbar first create gradient : Example directry created > R.drawable.gradient_contactus

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    >

    <gradient
        android:angle="90"
        android:startColor="#2980b9"
        android:centerColor="#6dd5fa"
        android:endColor="#2980b9">
    </gradient>


</shape>

and then set it like this :

getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.gradient_contactus));
Vaibhav
  • 21
  • 3
0

In onCreateView add this:

(activity as AppCompatActivity).supportActionBar?.title ="My APP Title"
Michel Fernandes
  • 1,187
  • 9
  • 8
0

If using a fragment, the best way is just to add a label element inside the fragment.xml (not manifest)

Example:

android:label="Your text.."
Aldan
  • 674
  • 9
  • 23