通过数据绑定将字符串传递给包含的布局不起作用

7

我正试图使用Android数据绑定功能将一个简单的字符串从主布局传递到include布局。它可以编译通过,但是传递给include的值实际上没有被传递。也就是说,在我的布局中没有显示出来。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable name="mytitle" type="java.lang.String"/>
    </data>

    <android.support.constraint.ConstraintLayout
        android:background="@color/black_background"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

 <include
            android:id="@+id/include1"
            layout="@layout/mylayout"
            app:mytitle="@{@string/categories}"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"/>

    </android.support.constraint.ConstraintLayout>
</layout>

我的Include布局是:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable name="mytitle" type="java.lang.String"/>
    </data>

<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="@color/black_background"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/category_header_textview"
        style="@style/WhiteText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{mytitle}"
        app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>
</layout>
1个回答

8

好的。我已经想到了。在这里发布给其他人参考。

我之前忽略了使用DataBindingUtil来设置内容视图。

请在您的onCreate()中添加以下内容:

DataBindingUtil.setContentView(this, R.layout.mylayout);

太好了:D,显然直接使用setContentView()无法使用数据绑定。 - Khemraj Sharma

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接