简体   繁体   中英

android 2-way data-binding kotlin mthod not being called

I want 2 way data-binding in android view-model.

So in XML, I put this:

            <EditText
                android:text="@={login.username}"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:textColor="@color/colorWhite" />

In my view-model I have:


    private val username = ObservableField<String>("")
    fun getUsername(): String? {
        Log.d("test",username.get())
        return username.get()
    }
    fun setUsername(username: String) {
        Log.d("test",username)
        this.username.set(username)
    }

But funny part none of these two method is being called. How can I resolve this. I can't just make them public, and expose them, so other class-es can just change their reference.

After learning, val is immutable, I made them public. Still it doesn't work and removed all those, getter and setter.

You can use LiveData here. If you want access to the string to be private, Create a

private val _username= MutableLiveData<String>("")

And declare your current exposed variable assigning it to the private one:

val username: LiveData<String> = _username

Then whenever you need to update the value, you post a new value to the private variable.

_username.postValue("new value")

OR

if you want non-private access to the value, then keep only the first one and change it's access modifier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM