简体   繁体   English

Android Jetpack Compose - MVVM 在 TextField 上重构

[英]Android Jetpack Compose - MVVM recompose on TextField

Trying to get a TextField to recompose using the MVVM pattern doesn't seem to work?尝试使用 MVVM 模式重新组合 TextField 似乎不起作用?

I get the input when I do Log.d but zero recomposition happening.我在执行 Log.d 时得到了输入,但发生了零重组。 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?似乎所有的例子都在可组合内做所有事情,而不是使用 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:请参见以下代码在 onCreate 方法中实例化 ViewModel class:

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
    })
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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