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.

3
  • 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 help? Commented Aug 18, 2020 at 9:14
  • because in ViewModel I need to the width text view for a logic code Commented Aug 18, 2020 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 Commented Aug 18, 2020 at 10:40

1 Answer 1

1

Replace :

android:layout_width="wrap_content"

with

android:layout_width="@{viewModel.priceTextViewWidth}"
Sign up to request clarification or add additional context in comments.

4 Comments

I need to use android:layout_width to wrap_content value and get size in view model
I need to detect if width change in XML , view model detect
So your question is to get the dimensions of the textview in the inflated layout?
yes, but I won't pass these dimensions from activity to view model. I like to from XML to view model directly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.