0

I have a question about how the visibility of an object in the ViewModel will change.

I'll tell you my case: I have a login interface that has two Edittexts and two buttons, a button and an Edittext are invisible by default, and I want the button that is visible to make the first Edittext and the button that I clicked invisible and make the second button and the second Edittext visible. And here's the problem, I could do all this in Activity, but I need to do it in ViewModel and I have no idea how to access the xml components from there.

I know all this is messy so I'll send the classes and if someone could tell me how to do this I'd appreciate it. Thank you. Thank you.

Login XML:

<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="viewModel"
        type="com.quobis.sippo.ecco.viewmodel.LoginViewModel"/>
</data>
<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="LoginUser">

    <ImageView
        android:layout_width="250dp"
        android:layout_height="200dp"
        android:src="@drawable/logom"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.2"
    />


    <EditText
        android:id="@+id/usr"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:hint="@string/hint_user"
        android:textSize="18sp"
        android:textColorPrimary="@color/colorLetterLogin"
        android:backgroundTint="@color/colorBackButtLogin"
        android:elevation="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginLeft="60dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.6"
        app:addTextChangedListener="@{viewModel.emailTextWatcher}"
    />

    <Button
        android:id="@+id/btn_usr"
        android:layout_width="55dp"
        android:layout_height="50dp"
        android:background="@color/colorBackButtLogin"
        android:drawableBottom="@drawable/ic_keyboard_arrow_right"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginLeft="260dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.6"
        android:onClick="@{viewModel::onUserClicked}"
    />

    <EditText
        android:id="@+id/pass"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:hint="@string/hint_pass"
        android:textSize="18sp"
        android:shape="rectangle"
        android:inputType="textPassword"
        android:textColorPrimary="@color/colorLetterLogin"
        android:backgroundTint="@color/colorBackButtLogin"
        android:elevation="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginLeft="60dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.6"
        android:visibility="invisible"
        android:onClick="@{viewModel::onLoginClicked}"
        />

    <Button
        android:id="@+id/btn_pass"
        android:layout_width="55dp"
        android:layout_height="50dp"
        android:background="@color/colorBackButtLogin"
        android:drawableBottom="@drawable/ic_keyboard_arrow_right"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginLeft="260dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.6"
        android:visibility="invisible"
        />

    <Spinner
        android:id="@+id/spinner_usr"
        android:layout_width="120dp"
        android:layout_height="40dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginLeft="40dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.85"
    />
</android.support.constraint.ConstraintLayout>
</layout>

ViewModel:

class LoginViewModel(private val listener: LoginResultCallbacks) : 
ViewModel() {
private val user: UserModel
var userp ="jorge"




init {
    this.user= UserModel(email = "")
}


fun emailTextWatcher(): TextWatcher {
    return object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            user.setEmail(s.toString())
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }


        override fun afterTextChanged(s: Editable) {

        }
    }

}

fun onUserClicked(v: View) {


}

fun onLoginClicked(v:View) {
    if (user.getEmail() == userp)
        listener.onSucces("Correcto")
    else
        listener.onError("Fallo")
}
}

Note: the method to change the visibility would be the onUserClicked.

Main activity:

class LoginUser : AppCompatActivity(), LoginResultCallbacks {
lateinit var binding: ActivityLoginUserBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView(this, R.layout.activity_login_user)
    binding.viewModel = ViewModelProviders.of(this, LoginViewModelFactory(this)).get(LoginViewModel::class.java)


    var languages = arrayOf("English", "Español", "Galego")
    val spinner = binding.spinnerUsr
    if (spinner != null) {
        val arrayAdapter = ArrayAdapter(this, R.layout.spinner_item, languages)
        spinner.adapter = arrayAdapter
    }

}


override fun onSucces(message: String) {
    Toast.makeText(this,"Login bueno", Toast.LENGTH_SHORT).show()
}

@SuppressLint("ResourceAsColor")
override fun onError(message: String) {
    binding.btnUsr
    btn_usr.setBackgroundColor(R.color.colorFailLogin)
}
}
5

You can use Android databinding. I will provide a rough example.

You need to create ObservableFields that your views in XML can bind to. For example

val isVisible : ObservableField<Boolean> = ObservableField();

Then create a binding adapter

@BindingAdapter("customVisibility")
fun setVisibility(view : View, visible : Boolean) {
    view.visibility = if (visible) View.VISIBLE else View.INVISIBLE
}

Then bind in your XML

app:customVisibility="@{viewModel.isVisible}"

Then you can change the visibility of the views just by modifying the isVisible property of your view model.

I have wrote a primer in Android Databinding and Functional MVVM. You can check it for further details (written in Kotlin) https://medium.com/tompee/android-data-binding-and-functional-mvvm-b311e4c98d

3
  • Thanks for the answer but that BindingAdapter gives me a lot of mistakes. It is unable to resolve the reference of visible and unexpected tokens. Apr 23 '18 at 9:13
  • I modified the code to compile as is. As for the binding adapter function, this should be a top level method or a static function (companion object).
    – tompee
    Apr 23 '18 at 9:48
  • Sorry to bother you again, but compiling gives me this error: e: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors. Apr 23 '18 at 10:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.