Kotlin系列二(Kotlin实现RecyclerView加item点击处理)

上一篇分享了kotlin基础语法,这一篇分享kotlin在Android开发中的实际应用,希望对正在学习的小伙伴有帮助。

添加的依赖:

/*RecyclerView*/
implementation 'com.android.support:recyclerview-v7:26.1.0'
/*retrofit*/
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
/*Okhttp*/
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.2.0'
/*rxjava*/
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
/*glide*/
compile 'com.github.bumptech.glide:glide:3.7.0'

Activity代码:

class MainActivity: AppCompatActivity() {

    val BASE_URL: String = "http://112.124.22.238:8081"

    private var mAPIService: APIService? = null

    var mDataList: ArrayList = ArrayList()

    init {
        mAPIService = initRetrofitClient()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        rv_main_content.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        rv_main_content.adapter = MainRecyclerAdapter(this, mDataList, ClickCallback())
        refreshData()
    }

    private fun refreshData(){
        //本地伪数据
		//return (0..25).mapTo(ArrayList()) { MainDataBean("${it}".toInt(), "test data $it", 0, "" )}
        //网络请求数据
        mAPIService!!.onRequestBannerData(1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({ responseData ->
                    mDataList.addAll(responseData)
                    rv_main_content.adapter.notifyDataSetChanged()
                })
    }

    inner class ClickCallback: OnClickCallback {
        override fun onClick(view: View, position: Int) {
            val tvId: TextView = view.findViewById(R.id.tv_main_item_id)
            val tvName: TextView = view.findViewById(R.id.tv_main_item_name)
            showToast(this@MainActivity, "position:$position, name:${tvId.text},name:${tvName.text}")
        }
    }

	//显示Toast
    private fun showToast(context: Context, message: String, duration: Int = Toast.LENGTH_SHORT) {
        Toast.makeText(context, message, duration).show()
    }

	//Retrofit
    private fun initRetrofitClient(): APIService {
        return Retrofit.Builder()
                        .baseUrl(BASE_URL)
                        .client(initOkHttpClient())
                        .addConverterFactory(GsonConverterFactory.create())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .build()
                        .create(APIService::class.java)
    }

	//OkhttpClient
    private fun initOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
                        .connectTimeout(5, TimeUnit.SECONDS)
                        .writeTimeout(5, TimeUnit.SECONDS)
                        .readTimeout(5, TimeUnit.SECONDS)
                        .build()
    }
}

Adapter代码:

class MainRecyclerAdapter(context: Context, dataBeanList: ArrayList, onClickCallback: OnClickCallback)
    : RecyclerView.Adapter() {

    private var mContext = context
    private var mDataBeanList = dataBeanList
    private var mOnClickCallback = onClickCallback

    override fun onBindViewHolder(holder: MainRecyclerViewHolder?, position: Int) {
        var mainDataBean: MainDataBean = mDataBeanList[position]
        Glide.with(mContext).load(mainDataBean.imgUrl).into(holder?.tvImg)
        holder?.tvId?.text = mainDataBean.id.toString()
        holder?.tvName?.text = mainDataBean.name
        holder?.itemView?.tag = position
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): MainRecyclerViewHolder {
        val view: View = LayoutInflater.from(mContext).inflate(R.layout.item_main, parent, false)
        view.setOnClickListener(ClickListener())
        return MainRecyclerViewHolder(view)
    }

    override fun getItemCount(): Int {
        return mDataBeanList.size
    }

    inner class MainRecyclerViewHolder(view: View): RecyclerView.ViewHolder(view) {
        var tvImg: ImageView = view.findViewById(R.id.iv_main_item_img)
        var tvId: TextView = view.findViewById(R.id.tv_main_item_id)
        var tvName: TextView = view.findViewById(R.id.tv_main_item_name)
    }

    inner class ClickListener: View.OnClickListener {
        override fun onClick(v: View?) {
            mOnClickCallback.onClick(v!!, v.tag as Int)
        }
    }
}

处理Item点击回调的接口:

interface OnClickCallback {
    fun onClick(view: View, position: Int)
}

Retrofit的api接口:

interface APIService {
    @GET("/course_api/banner/query?")
    fun onRequestBannerData(@Query("type") id: Int): Observable>
}

Data class:

data class MainDataBean(var id: Int, var name: String, var type: Int, var imgUrl: String)

你可能感兴趣的:(Android)