Migrate RecyclerView.ViewHolder from Java to Kotlin
- Kotlin class properties 取代了 Java 构造器和通过构造器初始化的field;
- Kotlin class 继承父类时直接把参数传递给父类,类似 Java 构造器执行
super(itemView)
; - 构造器执行的初始化代码被移到了
init {}
代码块; - Kotlin view binding 替代 ButterKnife
Java codes:
- public class ArticleItemViewHolder
- extends RecyclerView.ViewHolder {
+ class ArticleItemViewHolder(
+ private val mItemView: View,
+ private val mImageLoader: BaseImageLoader
+ ) : RecyclerView.ViewHolder(mItemView) {
- private View mItemView;
- private BaseImageLoader mImageLoader;
- private Consumer<View> mOnItemClickAction;
+ private var mOnItemClickAction: Consumer<View>? = null
- @BindView(R.id.article_title_view)
- TextView mTitleView;
- public ArticleItemViewHolder(View itemView, BaseImageLoader imageLoader) {
- super(itemView);
- ButterKnife.bind(this, itemView);
- itemView.setOnClickListener(...);
- mItemView = itemView;
- mImageLoader = imageLoader;
- }
+ init {
+ itemView.setOnClickListener { // point4: lambda 表达式
+ mOnItemClickAction?.accept(mItemView.articleImageView)
+ }
+ }
- public void bindArticle(ArticleItem articleItem) {
- mTitleView.setText(articleItem.getTitle());
- }
+ fun bindArticle(articleItem: ArticleItem) {
+ mItemView.articleTitleView.text = articleItem.title
+ }
2018-08-27 Weiyi Li