How to update toolbar title?

Viewed 1777

I want to update the title of my toolbar programmatically after changes have been made to an entity that is bound to the layout via data binding.

Excerpt from my layout (data binding works fine when bound initially):

androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:popupTheme="@style/AppTheme.PopupOverlay"
                    app:title="@{entity.title}"/>

My activity's onCreate method:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidInjection.inject(this);

        binding = DataBindingUtil.setContentView(this, R.layout.my_layout);

        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        MyEntity entity = (MyEntity) getIntent().getSerializableExtra(MyEntity.class.getName());
        binding.setEntity(entity);
    }

When the entity is edited I want to update the UI which I tried the following way in my activity:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   ...
   binding.setEntity(editedEntity); // this seems not to be sufficient and getSupportActionBar().getTitle() still returns the old value
   binding.toolbar.setTitle(editedEntity.getTitle()); // getSupportActionBar().getTitle() returns the updated value but the UI does not show it
   setSupportActionBar(binding.toolbar); // does not help either
   ...
}

So, the problem is that although I can debug and verify that getSupportActionBar().getTitle() returns the new and updated title at some point, this change is not reflected in the UI.

How can I force an update of my toolbar?

2 Answers

you can set title using,

getSupportActionBar().setTitle("title");

You may try using

getSupportActionBar().getTitle() 
setSupportActionBar(binding.toolbar); 
getSupportActionBar().setTitle(editedEntity.getTitle()); 

Just changed the sequence of setting title of toolbar and setting toolbar as supportActionBar.

Related