【问题标题】:Android Data Binding SetSupportActionBarAndroid 数据绑定 SetSupportActionBar
【发布时间】:2016-04-10 18:26:11
【问题描述】:

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

谢谢

【问题讨论】:

标签: android xml android-toolbar


【解决方案1】:

可以访问工具栏的实例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 组件中(引用 &lt;include/&gt;),您仍然可以访问它,只要您提供 @id&lt;include/&gt;

【讨论】:

  • 如果工具栏包含在包含布局中怎么办?或者如果包含的布局中有多个视图?
  • 我在自定义工具栏中使用了DataBinding,并使用了&lt;include&gt;,工具栏在activity_main.xml中使用,但我没有在activity_main.xml中使用DataBinding,那么如何获得@ mainActivity 中的 987654333@。
  • 如果binding.root.toolbar&lt;include&gt;里面呢?
【解决方案2】:

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

ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
setSupportActionBar(binding.toolbar);

【讨论】:

    【解决方案3】:
    <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>
    

    【讨论】:

    • 能否分享更改标题的视图模型代码?
    【解决方案4】:

    您可以这样使用它。经过多次搜索后,这回答了我。

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

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

    【讨论】:

      猜你喜欢
      • 2019-01-24
      • 2016-03-06
      • 1970-01-01
      • 1970-01-01
      • 2017-07-28
      • 2021-05-24
      • 2020-11-12
      • 2016-06-19
      • 2015-09-05
      相关资源
      最近更新 更多