android - 如何更新工具栏标题?

标签 android android-actionbar android-databinding

这个问题在这里已经有了答案:





Android SupportActionBar does not refresh title

(1 个回答)


2年前关闭。




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

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

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}"/>

我的 Activity 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);
    }

编辑实体时,我想更新我在 Activity 中尝试以下方式的 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
   ...
}

所以,问题是虽然我可以调试和验证 getSupportActionBar().getTitle()在某个时候返回新的和更新的标题,此更改不会反射(reflect)在 UI 中。

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

最佳答案

您可以使用设置标题,

getSupportActionBar().setTitle("title");

关于android - 如何更新工具栏标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60703829/

相关文章:

android - ActionBar 选项卡背景与 xml

android - 有任何 ActionBar 可见性更改事件监听器

android - ActionBar 的大小(以像素为单位)是多少?

android - 无法在android中的SQLite中插入记录

仅指向 URL 的 Android 应用

android - 我可以在可绘制文件夹中有一个 XML 支持多个按钮的多种颜色/边框吗?

java - 无法使用 Android 数据绑定(bind)进行双重绑定(bind)

android - 在Android中的recylerview上实现 map 时,Google Map返回空对象引用

Android数据绑定(bind)问题: Missing return statement in generated code while using with a custom view?

java - 如何让按钮永久不可点击