简体   繁体   中英

Android Jetpack Compose - MVVM recompose on TextField

Trying to get a TextField to recompose using the MVVM pattern doesn't seem to work?

I get the input when I do Log.d but zero recomposition happening. Searched all over and cannot seem to find a "simple" solution to this... there must be a logical answer:-)

It seems all the examples are doing everything inside the composable and not using MVVM?

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            TextFieldRecomposeTheme {
                Surface(color = MaterialTheme.colors.background) {
                    GetInput(myVM = MyViewModel())
                }
            }
        }
    }
}

@Composable
fun GetInput(myVM: MyViewModel) {

    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {

        OutlinedTextField(
            value = myVM.updatedClientData.firstName,
            onValueChange = { myVM.updatedClientData.firstName = it },
            label = { Text(text = "Firstname")}
        )
    }

}

class MyViewModel() : ViewModel() {

    var updatedClientData by mutableStateOf<Client>(Client())

    // This is just for testing - the data will be loaded from a remote server and set
    init {
        updatedClientData = Client(
            id = 1,
            firstName = "Test",
            lastName = "User",
            email = "test.user@domain.com",
            mobilePhone = "777666555"
        )
    }
}

data class Client(
    @SerializedName("Id")
    val id: Int = 0,
    @SerializedName("FirstName")
    var firstName: String = "",
    @SerializedName("LastName")
    val lastName: String = "",
    @SerializedName("Email")
    val email: String = "",
    @SerializedName("MobilePhone")
    val mobilePhone: String = "",
)

See the following code to instantiate the ViewModel class in the onCreate method:

class MyActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    // Create a ViewModel the first time the system calls an activity's onCreate() method.
    // Re-created activities receive the same MyViewModel instance created by the first activity.

    // Use the 'by viewModels()' Kotlin property delegate
    // from the activity-ktx artifact
    val model: MyViewModel by viewModels()
    model.getUsers().observe(this, Observer<List<User>>{ users ->
        // update UI
    })
}

}

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