Andorid: 布局数据变量:XML文件中不能使用ViewModel类。

问题描述 投票:0回答:1

我对连接ViewModel直接到XML文件的概念很陌生,我真的不知道为什么Gradle找不到ViewModel类。

Bellow我发布我的代码和错误日志。

先谢谢大家的帮助。

EDIT : Main Activity只是Host for the fragment,而这个Fragment实例化ViewModel。

代码

<?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="tvm"
            type="com.uj.bachelor_jlk700.examsystem.screens.test.TestViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".screens.test.TestFragment">


        <TextView
            android:id="@+id/textView_testFragment_name"
            android:layout_width="90dp"
            android:layout_height="30dp"
            android:text="@{tvm.userName}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.049"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.035" />

错误的MSG

C:\Users\Jan\AndroidStudioProjects\ExamSystem\app\build\generated\data_binding_base_class_source_out\debug\out\com\uj\bachelor_jlk700\examsystem\databinding\TestFragmentBinding.java:17: error: cannot find symbol
import com.uj.bachelor_jlk700.examsystem.screens.test.TestViewModel;
                                                     ^
  symbol:   class TestViewModel

查看模型

主要活动

片段-模型

android kotlin layout data-binding viewmodel
1个回答
1
投票

你的xml布局不能识别 电视机 对象,该对象指的是 TestViewModel 类,并且你需要明确地定义 TestViewModel 类中。

要在你的片段中的 onCreateView() 你的片段类的。

viewModel = ViewModelProviders...
binding.setTvm(viewModel)
© www.soinside.com 2019 - 2024. All rights reserved.