Hey guys I am using preview in my view holder. I am getting this weird issue in my @Preview
annotation. I am unable to understand this.
Preview must be a top level declarations or in a top level class with a default constructor.
OptionsViewHolder.kt
class OptionsViewHolder(val binding: ItemLayoutBinding) : Recyclerview.ViewHolder(binding.root) {
private val context = binding.root.context
companion object {
fun from(parent: ViewGroup): OptionsViewHolder {
return OptionsViewHolder(
ItemLayoutBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
}
fun bindChoice() {
binding.itemComposable.setContent {
Options()
}
}
@Composable
fun Options() {
xyz..
}
@Preview
@Composable
fun OptionsPreview(){
Options()
}
}
CodePudding user response:
As the error indicates. Previews must either be top-level functions (functions outside a class) or be in a class with a default constructor.
My recommendation would be to either extract your composable and preview out of the class in the same file or extract them into a separate file all together and have the content composable and viewholder separated.
OptionsViewHolder.kt
class OptionsViewHolder(val binding: ItemLayoutBinding) : Recyclerview.ViewHolder(binding.root) {
private val context = binding.root.context
companion object {
fun from(parent: ViewGroup): OptionsViewHolder {
return OptionsViewHolder(
ItemLayoutBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
}
fun bindChoice() {
binding.itemComposable.setContent {
Options()
}
}
}
@Composable
fun Options() {
xyz..
}
@Preview
@Composable
fun OptionsPreview() {
Options()
}