【问题标题】:how can get attribute view in xml from viewModel如何从 viewModel 获取 xml 中的属性视图
【发布时间】:2020-12-07 10:07:07
【问题描述】:

我有 3 个文件(Activity、ViewModel、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">

    <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>

ViewModel.class

open class MainViewModel : ViewModel() {

    val price = MutableLiveData<String>()
    val priceTextViewWidth = MutableLiveData<Int>()

}

在活动中,我将 XML 连接到视图模型

 binding.viewModel = viewModel

我可以在 View Model 中通过更改价格变量来更新 Textview,但 我需要将 TextView 宽度传递给 ViewModel 中的 priceTextViewWidth

【问题讨论】:

  • I need to pass TextView width to priceTextViewWidth in ViewModel. 所以你想将 ViewModel 中的变量设置为等于 View 的宽度?我能问为什么吗? this 也有帮助吗?
  • 因为在 ViewModel 中我需要一个逻辑代码的宽度文本视图
  • 我认为如果不涉及 Activity,您将无法做到这一点。需要它的逻辑是什么?令人惊讶的是,某些内容的显示方式会影响业务逻辑

标签: java android kotlin data-binding viewmodel


【解决方案1】:

替换:

android:layout_width="wrap_content"

android:layout_width="@{viewModel.priceTextViewWidth}"

【讨论】:

  • 我需要使用 android:layout_width 来包装内容值并在视图模型中获取大小
  • 我需要检测 XML 中的宽度是否发生变化,视图模型检测
  • 所以你的问题是在膨胀的布局中获取文本视图的尺寸?
  • 是的,但我不会将这些维度从活动传递到视图模型。我喜欢从 XML 直接查看模型
猜你喜欢
  • 1970-01-01
  • 2012-10-01
  • 2015-02-02
  • 1970-01-01
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
  • 2013-11-21
  • 1970-01-01
相关资源
最近更新 更多