0

In an activity file, when I write getSupportActionBar().setTitle(...) in an instantiated observer interface for a view model's LiveData value, the action bar's title doesn't change on the observable's updates.

Toolbar setup inside the onCreate method in my activity file:

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

mViewModel.getValue().observe(this, mValue -> getSupportActionBar().setTitle(mValue));

The field definition and getter code of mValue in my view model:

protected MutableLiveData<String> mValue = new MutableLiveData();
public LiveData<String> getValue() {
    return mValue;
}

To clarify, the observable's value (e.g. mValue) is being passed to the lambda observer in the activity file, as expected. And setSupportActionBar().setTitle() works like expected when called like normal i.e. outside the lambda observer, also as expected.

honno
  • 53
  • 1
  • 6

1 Answers1

0

I found a solution (thanks to user1506104) to changing the toolbar's title, which did not use getSupportActionBar().setTitle().

CollapsingToolbarLayout toolbarLayout = findViewById(R.id.toolbar_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

mViewModel.getValue().observe(this, mValue -> {
    toolbarLayout.setTitle(mValue);
});

Where R.id.toolbar_layout is the CollapsingToolbarLayout that parents R.id.toolbar in the activity's respective layout resource.

I do not know why it works unfortunately.

honno
  • 53
  • 1
  • 6