Java 如何从viewModel获取xml中的属性视图
我有3个文件(活动、视图模型、XML) 我使用MVVM并将XML连接到ViewModelJava 如何从viewModel获取xml中的属性视图,java,android,kotlin,data-binding,viewmodel,Java,Android,Kotlin,Data Binding,Viewmodel,我有3个文件(活动、视图模型、XML) 我使用MVVM并将XML连接到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&
<?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">
<data>
<variable
name="viewModel"
type="com.example.MainViewModel"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/priceTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@={viewModel.price}"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
我可以使用视图模型中的change price变量更新Textview,但我需要将Textview width传递给ViewModel中的priceTextViewWidth替换:
android:layout_width="wrap_content"
与
我需要将TextView width传递给ViewModel中的priceTextViewWidth。
那么您想将ViewModel中的变量设置为与视图宽度相等吗?我能问一下为什么吗?也有帮助吗?因为在ViewModel中,我需要为逻辑代码设置宽度文本视图,我认为在不涉及活动的情况下,您无法做到这一点。需要它的逻辑是什么?我发现有些东西的显示方式会影响业务逻辑,这让我很惊讶。我需要使用android:layout\u width来包装内容值,并在视图模型中获取大小。我需要检测XML中的宽度是否发生变化,视图模型是否检测。所以,您的问题是在膨胀的布局中获取文本视图的尺寸?是,但我不会将这些维度从活动传递到视图模型。我喜欢从XML直接查看模型
binding.viewModel = viewModel
android:layout_width="wrap_content"
android:layout_width="@{viewModel.priceTextViewWidth}"