How to change the text on the action bar

2018-12-31 16:21发布

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.

13条回答
琉璃瓶的回忆
2楼-- · 2018-12-31 16:42

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

    }
}
查看更多
永恒的永恒
3楼-- · 2018-12-31 16:42

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

getSupportActionBar().setTitle("Whatever title");
查看更多
旧人旧事旧时光
4楼-- · 2018-12-31 16:42

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>
查看更多
闭嘴吧你
5楼-- · 2018-12-31 16:44

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.

查看更多
姐姐魅力值爆表
6楼-- · 2018-12-31 16:45

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.

查看更多
柔情千种
7楼-- · 2018-12-31 16:47
getActionBar().setTitle("edit your text"); 
查看更多
登录 后发表回答