I learn the use of ViewHolder from an offical sample named UserViewHolder.
public class UserViewHolder extends RecyclerView.ViewHolder {
static UserViewHolder create(LayoutInflater inflater, ViewGroup parent) {
UserItemBinding binding = UserItemBinding
.inflate(inflater, parent, false);
return new UserViewHolder(binding);
}
private UserItemBinding mBinding;
private UserViewHolder(UserItemBinding binding) {
super(binding.getRoot());
mBinding = binding;
}
public void bindTo(User user) {
mBinding.setUser(user);
mBinding.executePendingBindings();
}
}
I'm going to write many ViewHolder
classes, so I hope I can write an abstract class. In Java, it looks like:
public abstract static class BaseViewHolder {
abstract static BaseViewHolder create()
abstract void bindTo()
}
I try to write it using Kotlin , but finally I find that it's not as simple as it in Java.
abstract class BaseViewHolder(itemView: View):RecyclerView.ViewHolder(itemView) {
abstract fun bindTo(viewModel: BaseViewModel)
}
In Kotlin, if I want a static function, I need to write the function in "companion objects". But it can't be a "abstract".
In Java, a abstract class with abstract classes is common.
But how can I write it in Kotlin?
update:
I have wrote my own SleepViewHolder. I'm going to write lots of ViewHolder, such as AppleViewHolder, BananaViewHolder and so on. So I want to build a BaseViewHolder as a pattern. My question is that, in that case, what's the best way to write the pattern BaseViewHolder? Should I change the constrcuter of it, or make the create function public?
open class SleepViewHolder private constructor(private val binding: ItemSleepBinding)
: RecyclerView.ViewHolder(binding.root) {
companion object {
@JvmStatic
fun create(inflater: LayoutInflater, parent: ViewGroup): SleepViewHolder {
val binding: ItemSleepBinding
= DataBindingUtil.inflate(inflater, R.layout.fragment_base, parent, false)
return SleepViewHolder(binding)
}
}
open fun bindTo(viewmodel: SleepViewModel) {
binding.vm = viewmodel
binding.executePendingBindings()
}
}