Issue
So this project that I am involved in has me using Jetpack Compose to create my layouts for the first time. So I am pretty new to this. I have data classes that stored the data in them from an API. ViewModel/LiveData is also in use as well. My question is how do you get the TextView to show the data stored in the data models? Any and all answers are welcomed. Thank You.
Solution
First of all, create a ViewModel for your screen through viewModel()
. e.g.
val myViewModel: MyViewModel = viewModel()
or
val myViewModel: MyViewModel = hiltViewModel()
for DaggerHilt. (if you can't access those functions, try adding androidx.lifecycle:lifecycle-viewmodel-compose:2.4.1
for viewModel()
and androidx.hilt:hilt-navigation-compose:1.0.0
for hiltViewModel()
—be mindful that these versions are likely outdated).
Next, pass or inject your repository or UseCase into the ViewModel's constructor and create a state variable to hold and update your text.
@HiltViewModel
class MyViewModel @Inject constructor(
private val myRepository: MyRepository
): ViewModel() {
var text by mutableStateOf("")
private set
fun setNewText(newText: String) {
text = newText
}
init {
viewModelScope.launch { // in case it's a suspend function
setNewText(myRepository.getDataClass().getText())
}
}
}
(for mutableStateOf
getter and setter delegation, you need to import androidx.compose.runtime.getValue
and androidx.compose.runtime.setValue
).
Finally, create the Text
in your Composable function, call the ViewModel and use it to update your newly created text.
@Composable
fun MyScreen(myViewModel: MyViewModel = hiltViewModel()) {
Text(
text = myViewModel.text,
modifier = Modifier.fillMaxWidth() // modify it as you wish
)
}
If that doesn't suit your needs, please provide more details on your situation. Also, I'd recommend you check out the documentation if you have any doubts regarding what I've shown you.
Answered By - Dannly
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.