Простое использование provider
data class User(
val userName: String
)
class SimpleUserProvider() : PreviewParameterProvider<User> {
override val values = sequenceOf(User(userName = "Stephen"))
}
@Preview(showBackground = true)
@Composable
fun Greeting(@PreviewParameter(SimpleUserProvider::class) user: User) {
Text(text = "Hello ${user.userName}!")
}
Класс для mock, без лишних инстансов
data class User(
val userName: String,
val userSurname: String,
val userPassword: String,
val userCity: String,
val userAge: String
)
class SimpleGreetingProvider() : PreviewParameterProvider<List<User>> {
override val values = sequenceOf(
listOf(
User(
userName = "Stephen",
userSurname = "King",
userPassword = "qwerty",
userCity = "Main",
userAge = "12-15-1983"
),
User(
userName = "Christine",
userSurname = "Bloom",
userPassword = "qwerty1234",
userCity = "Chicago",
userAge = "05-23-1964"
)
)
)
}
@Preview(showBackground = true)
@Composable
fun UserList(@PreviewParameter(SimpleGreetingProvider::class) userList: List<User>) {
LazyColumn {
items(userList) {
Text(it.toString())
}
}
}
Класс для mock, который принимает коллекцию
data class User(
val userName: String,
val userSurname: String,
val userPassword: String,
val userCity: String,
val userAge: String
) {
companion object {
fun getMockUsers() = listOf(
User(
userName = "Stephen",
userSurname = "King",
userPassword = "qwerty",
userCity = "Main",
userAge = "12-15-1983"
),
User(
userName = "Christine",
userSurname = "Bloom",
userPassword = "qwerty1234",
userCity = "Chicago",
userAge = "05-23-1964"
)
)
}
}
class SimpleUserProvider() : CollectionPreviewParameterProvider<User>(User.getMockUsers())
@Preview(showBackground = true)
@Composable
fun UserList(@PreviewParameter(SimpleUserProvider::class) userList: User) {
Text(userList.toString())
}
Класс для создания Pair из двух provide классов
open class PreviewParameterCombiner<T, U>(
private val first: PreviewParameterProvider<T>,
private val second: PreviewParameterProvider<U>,
) : PreviewParameterProvider<Pair<T, U>> {
override val values = first.values.flatMap { firstValue ->
second.values.map { secondValue ->
firstValue to secondValue
}
}
}
Пример использования Pair в mock
class UserIds : CollectionPreviewParameterProvider<String>(listOf("Name", "Age"))
class DarkThemePreviewParamProvider : CollectionPreviewParameterProvider<Boolean>(listOf(true, false))
class User : PreviewParameterCombiner<String, Boolean>(UserIds(), DarkThemePreviewParamProvider())
@Preview(showBackground = true)
@Composable
fun UserList(@PreviewParameter(User::class) user: Pair<String, Boolean>) {
JetpackComposeBookTheme(darkTheme = user.second) {
Surface(color = MaterialTheme.colors.background) {
Text(user.first)
}
}
}