1

I try to change the title of my MainActivity outside the onCreate() method. It seems to work inside onCreate(), but if I try to change it programmatically, it doesn't do anything.

My onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(true);
    getSupportActionBar().setTitle(selectedSong);

I already tried outside the onCreate():

 public void updatetitle(String title) {
        toolbar.setTitle(title);
        getSupportActionBar().setTitle(selectedSong);
        ((MainActivity) this).getSupportActionBar().setTitle(selectedSong);
        setTitle(selectedSong); 
}

None of these works. When I debug the code. The code in the toolbar object is updated, but the view isn't refreshed. Any hints? Thanks.

MTwain
  • 33
  • 9

1 Answers1

0

Write setTitle() on top in onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setTitle(selectedSong); //*
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(true);
godot
  • 3,422
  • 6
  • 25
  • 42
  • I like to change the title outside onCreate. I am able to set it in onCreate, but later on, I can't updated. – MTwain Feb 12 '18 at 21:53