0

I have a 3 files(Activity, ViewModel,XML)

I use MVVM and connect XML to 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>()

}

and in the activity, I connect XML to view model with

 binding.viewModel = viewModel

I can update Textview with change price variable in View Model but I need to pass TextView width to priceTextViewWidth in ViewModel.

Rasoul Miri
  • 11,234
  • 1
  • 68
  • 78
  • 1
    `I need to pass TextView width to priceTextViewWidth in ViewModel.` so you want to set the variable in the ViewModel as equal to the View width? Can I ask why? Also does [this](https://stackoverflow.com/questions/18268915/views-getwidth-and-getheight-returning-0) help? – Stachu Aug 18 '20 at 09:14
  • because in ViewModel I need to the width text view for a logic code – Rasoul Miri Aug 18 '20 at 10:03
  • 1
    I don't think you can do that without involving Activity. What's the logic that requires it? I find it surprising that the way something is displayed affects the business logic – Stachu Aug 18 '20 at 10:40

1 Answers1

1

Replace :

android:layout_width="wrap_content"

with

android:layout_width="@{viewModel.priceTextViewWidth}"
Abhimanyu
  • 11,351
  • 7
  • 51
  • 121