协程是一个轻量级的线程,
在网络工具类中
object HttpUtils {
val fit = Retrofit.Builder()
.baseUrl(Contants.path1)
.addConverterFactory(GsonConverterFactory.create())
.client(OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().apply {
setLevel(HttpLoggingInterceptor.Level.BODY)
})
.build())
.build()
val api = fit.create(ApiService::class.java)
}
@GET(Contants.path2)
suspend fun getData() : JavaBean
页面显示
runBlocking {
val ban = async { HttpUtils.api.getData() }
xban.setBannerData(R.layout.xbanner,ban.await().result)
xban.loadImage { _, model, view, _ ->
(view as SimpleDraweeView).setImageURI((model as Result).imageUrl)
}
val rvData = async { HttpUtils.api.getData() }
rv_id1.adapter = MyAdapter(rvData.await().result)
rv_id2.adapter = MyAdapter(rvData.await().result)
}
适配器
class MyAdapter(val data: MutableList<Result>) : RecyclerView.Adapter<MyAdapter.ViewHolder>(){
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ViewHolder (
LayoutInflater.from(parent.context).inflate(R.layout.item1,parent,false)
)
override fun getItemCount(): Int = data.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
data[position].let {
holder.itemView.apply {
item_text.text = it.name
item_img.setImageURI(it.imageUrl)
setOnLongClickListener {
data.removeAt(position)
notifyDataSetChanged()
return@setOnLongClickListener true
}
}
}
}
}