Kotlin实现Retrofit网络请求RecyclerView展示图片列表
程序员文章站
2022-06-09 23:16:28
...
1.新建一个项目 选中lnclude kotlin support
2.然后导包
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.7.0'
compile 'com.google.code.gson:gson:2.8.0'
compile 'com.github.bumptech.glide:glide:4.2.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.2.0'
compile 'com.android.support:recyclerview-v7:26.1.0'
3.创建一个接口 当然创建有些不一样
4.然后点击Kind这一行 选择Interface
5. 接口地址:
http://route.showapi.com/197-1?showapi_appid=42684&showapi_sign=f6527e909abc4edea350ec8b9a9db0f5&num=10
接口代码 :interface PictureApi {
@POST("197-1")
@FormUrlEncoded
fun getPicture(@Field("showapi_appid") showapi_appid: String,
@Field("showapi_sign") showapi_sign: String,
@Field("num") num: Int) : Call<ImageBean>
}
6.创建一个实体类 这里还要装一个工具
File --> Settings --> Plugins --> 搜索 JsonToKotlinClass 然后安装即可
按住alt+k键弹出一个框 第一个Class Name填写ImageBean就行了,这里可以随便写,JSON Text就可以放置接口里面的JSON数据
第一排有三个Property,Annotation,other
Property—选择—>Val—选择—>lnit with default value(avoid null)
Annotation—选择—>Gson
然后点ok就会自动生成下面所示的代码
7.创建HttpManager网络请求类
class HttpManager {
var retrofit = Retrofit.Builder()
.baseUrl("http://route.showapi.com/") //基地址
.addConverterFactory(GsonConverterFactory.create())
.build()
fun getPicture(num: Int, success: (ImageBean) -> Unit, fail: (String) -> Unit) {
var pictureApi: PictureApi = retrofit.create(PictureApi::class.java)
var call: Call<ImageBean> = pictureApi.getPicture("42684", "f6527e909abc4edea350ec8b9a9db0f5", num)
call.enqueue(object : Callback<ImageBean> {
override fun onResponse(call: Call<ImageBean>?, response: Response<ImageBean>) {
success(response.body()!!)
}
override fun onFailure(call: Call<ImageBean>?, t: Throwable?) {
fail(t.toString())
}
})
}
}
8.主布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击我吧" />
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
9.item_rcy_picture布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/ImageView"
android:layout_width="wrap_content"
android:layout_height="180dp" />
</LinearLayout>
10.recyclerview适配器
class PictureAdapter(private var list: List<Newslist>) : RecyclerView.Adapter<PictureAdapter.MyViewHolder>() {
fun notifyDataChange(list: List<Newslist>) { //更新适配器数据
this.list = list
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return list.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
var view = LayoutInflater.from(parent.context).inflate(R.layout.item_rcy_picture, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.textView.text = list[position].title //展示图片标题
Glide.with(holder.imageView) //ImageView中展示图片
.load(list[position].picUrl)
.into(holder.imageView)
//这是图片点击事件
holder.imageView.setOnClickListener {
mListener?.invoke(position)
}
}
class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var textView: TextView = itemView.findViewById(R.id.TextView)
var imageView: ImageView = itemView.findViewById(R.id.ImageView)
}
var mListener: ((pos: Int) -> Unit)? = null
fun setOnItemClickListener(listener: ((pos: Int) -> Unit)) {
mListener = listener
}
}
11.主函数
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var adapter = PictureAdapter(ArrayList()) //适配器,默认一个空的集合,等网络请求后更新数据
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
button.setOnClickListener {
//按钮点击事件
HttpManager().getPicture(
10, //网络请求 5条数据 num表示网络请求返回的数据数量
{ adapter.notifyDataChange(it.showapiResBody.newslist) }, //成功的回掉接口
{ Toast.makeText(this, it, Toast.LENGTH_SHORT).show() } //失败的回掉接口
)
}
adapter.setOnItemClickListener {
Toast.makeText(this, it.toString(), Toast.LENGTH_SHORT).show()
}
}
}
12.最后别忘记加网络访问权限
<uses-permission android:name="android.permission.INTERNET" />
上一篇: JAVA实验报告