Android 数据绑定 SetSupportActionBar

Android Data Binding SetSupportActionBar

您好,我想知道是否有使用 Android 数据绑定库的此功能的 xml 标记,或者如何在没有 findViewById() 方法的情况下实现此功能

谢谢

您可以访问工具栏实例 using views by id 功能

<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

然后在您的 onCreate() 方法上执行以下操作

ActivityGalleryBinding binding = DataBindingUtil
    .setContentView(this, R.layout.activity_gallery);
binding.setViewModel(new GalleryModel(this));
//set it like this
setSupportActionBar(binding.<location>.<of>.<your>.toolbar);

如果您的工具栏位于其他 xml 组件内(用 <include/> 引用),您仍然可以访问它,只要您向 <include/>[提供和 @id

Android Studio中制作项目然后你可以使用下面的代码访问工具栏:

ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
setSupportActionBar(binding.toolbar);
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    >
  <data>
    <variable
        type="com.example.viewModel"
        name="viewModel"
        />
  </data>
  <android.support.v7.widget.Toolbar
      android:layout_width="match_parent"
      android:layout_height="?actionBarSize"
      app:title="@{viewModel.title}"/>
</layout>

你可以这样使用它。经过多次搜索,这为我解答了。

  1. 使用 id 作为您的包含,例如我的工具栏 ID 是 tb 并且包含 idmtoolbar

  2. 现在使用setSupportActionBar(mainBinding.mtoolbar.tb);