如何更新工具栏标题?

fla*_*rud 5 android android-actionbar android-databinding

我想在对通过数据绑定绑定到布局的实体进行更改后以编程方式更新工具栏的标题。

我的布局摘录(数据绑定在最初绑定时工作正常):

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}"/>
Run Code Online (Sandbox Code Playgroud)

我的活动onCreate方法:

    @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);
    }
Run Code Online (Sandbox Code Playgroud)

编辑实体时,我想更新 UI,我在活动中尝试了以下方式:

@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
   ...
}
Run Code Online (Sandbox Code Playgroud)

因此,问题是,虽然我可以调试和验证getSupportActionBar().getTitle()在某个时刻返回新的和更新的标题,但此更改并未反映在 UI 中。

如何强制更新我的工具栏?

Nir*_*raj 4

您可以使用设置标题,

getSupportActionBar().setTitle("title");
Run Code Online (Sandbox Code Playgroud)