Android 自定义kotlin中BaseRecyclerViewAdapter

我们在开发中总是要用到自定义适配器的,那么总是在用到的时候,直接继承显然已经不能满足我们去装13的心情了,那么直接上码吧

下面是BaseRecyclerViewAdapter.kt的源码内容:

abstract class BaseRecyclerViewAdpater<T, VH: RecyclerView.ViewHolder>(var mContext: Context): RecyclerView.Adapter<VH>() {

	var mItemClickListener: OnItemClickListener<T>? = null
	var dataList: MutableList<T> = mutableListOf()
	
	fun setData(source: MutableList<T>) {
        dataList = source
        notifyDataSetChanged()
    }

    fun addData(source: MutableList<T>) {
        dataList.addAll(source)
        notifyDataSetChanged()
    }
	
	override fun onBindViewHolder(holder: VH, position: Int) {
		holder.itemView.setOnClickListener {
			if (null != mItemClickListener) {
				mItemClickListener!!.onItemClick(dataList[position], position)
			}
		}
	}
	
	override fun getItemCount(): Int {
        return dataList.size
    }

	/**
	 * Item点击事件
	 */
	interface OnItemClickListener<in T> {
        fun onItemClick(item: T, position: Int)
    }
	
	/**
	 * 设置监听
	 */
	fun setOnItemClickListener(listener: OnItemClickListener<T>) {
        this.mItemClickListener = listener
    }
}

具体的使用方法

UserListAdapter.kt

class UserListAdapter(var context: Context): BaseRecyclerViewAdpater<UserInfo, UserListAdapter.UserHolder>(context) {
	
	override fun onCreateViewHolder(parent: ViewGroup, position: Int): UserHolder {
        val view = LayoutInflater.from(mContext).inflate(R.layout.item_user_info, parent, false)
        return UserHolder(view)
    }

	override fun onBindViewHolder(holder: UserHolder, position: Int) {
        super.onBindViewHolder(holder, position)
        val model = dataList[position]
        holder.itemView.txtItemUserName.text = model.userName
    }

	class UserHolder(view: View): RecyclerView.ViewHolder(view)
}

业务逻辑代码

MainActivity.kt

class MainActivity: AppCompatActivity() {
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_main)
		
		var adapter = UserListAdapter(this)
		adapter.setOnItemClickListener(object : BaseRecyclerViewAdapter.OnItemClickListener<UserInfo> {
            override fun onItemClick(item: UserInfo, position: Int) {
                // what you want to do
            }
        })
	}
}

以上就是所有的代码,希望对你有所帮助

你可能感兴趣的:(Android)