基于OKhttp、Gson和Handle的kotlin版RecyclerView
作者:互联网
这里写自定义目录标题
新手小白初次尝试的项目
新手第一次学习安卓使用的RecyclerVIew,有不当请提出。
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.finalrecycler">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Finalrecycler">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MyRecyclerView">
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
MainActivity.kt
package com.example.finalrecycler
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button_one:Button=findViewById(R.id.btn_one)
button_one.setOnClickListener( {
var intent =Intent(this,MyRecyclerView::class.java)//跳转到MyRecyclerView.kt上
Log.d("success","succussful")
startActivity(intent)
})
}
}
MainActivity.kt的xml文件 (activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_one"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="@color/white"
android:orientation="horizontal"
android:text="RecyclerView的Adapter"
android:textAllCaps="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
这是activity_main的界面
MyRecyclerView.kt
package com.example.finalrecycler
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import okhttp3.*
import java.io.IOException
import java.lang.Exception
class MyRecyclerView :AppCompatActivity() {
var responseData :String? ="null"
var madapter=ADA_RecyclerItem()
var examples :List<ResultBean>? =null
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.view_recycler)
var recyclerview =findViewById<RecyclerView>(R.id.recyclerview)
recyclerview.layoutManager=LinearLayoutManager(this)
recyclerview.adapter=madapter
getDataByGet()
}
private fun generateDummyList(size: Int): List<ResultBean>
{
val list = ArrayList<ResultBean>()//创造一个ResultBean的数组列表
try {
val gson = Gson()//构建Gson对象
var resultJson = gson.fromJson(responseData, ResultBean::class.java)//把responseData(Json的格式的字符串)转换为需要转换对象的类型(ResultBean::class.java)
for (i in 0 until size) {
val item = ResultBean(resultJson.data, resultJson.errorCode, resultJson.errorMsg)//目标数据类中最外层的变量都需要输入
list.add(item)//把item放入到ResultBean的数组列表list里面
Log.d("Test","list"+list.size.toString())
}
} catch (e: Exception) {
Log.e("test", e.toString())
}
return list
}
fun getDataByGet()
{
val client= OkHttpClient() //创建okhttpclient对象
val request= Request.Builder().get()//构造Request对象
.url("你的接口")
.build()
val call =client.newCall(request)//将Request封装成Call
//异步请求
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {//失败回应
Log.d("UPDATE","onFailyre:$e")
}
override fun onResponse(call: Call, response: Response) {//成功回应
responseData=response.body?.string()//把回应的主题变成string类型,赋值给responseData
Log.d("UPDATE","OnRespnes:"+responseData)
examples = (generateDummyList(5))//得到已经从接口中下载并通过Gson转换完成后的数组列表(ResultBean类型的)
var message = Message()//构建Message对象(因为android中不能通过非主线程来更新UI界面,故需要用message来把更新UI的需求来传递给主线程)
message.what = 0x1122//设置message对象的值,注意赋值给.what
handler.sendMessage(message)//发送message
}
})
}
var handler: Handler = object : Handler(Looper.getMainLooper()) {//handler是接受并处理的message类,注意这里一定要用object,否则无法重写handleMessage。
// 括号里面的(Looper.getMainLooper)是获取主线程的意思,表示现在在主线程中
override fun handleMessage(msg: Message) {//handleMessage是处理message的函数
super.handleMessage(msg)
if (msg.what == 0x1122) {
madapter.setDatas(examples)//该方法在ADA_RecyclerItem.kt中
}
}
}
}
MyRecyclerView.kt的xml文件(view_recycler.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
RecyclerView的Adapter( ADA_RecyclerItem.kt)
package com.example.finalrecycler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class ADA_RecyclerItem (): RecyclerView.Adapter<ADA_RecyclerItem.ViewHolder>()//RecyclerView的Adapter必须继承RecyclerView.Adapter<VH>,中间的VH是ViewHolder,我们需要在函数中构建
{
var recyclerViewList:List<ResultBean>? = null
open fun setDatas(dataList:List<ResultBean>?) {
this.recyclerViewList = dataList//把处理完成后的数据赋值给recyclerViewList
notifyDataSetChanged()//刷新UI界面,该函数只能在Adapter中使用
}
class ViewHolder ( itemView: View): RecyclerView.ViewHolder(itemView) {//初始化声明Adapter中需要使用到的控件
val chapterName:TextView=itemView.findViewById(R.id.tv_chapterName)
val author:TextView=itemView.findViewById(R.id.tv_author)
val link:TextView=itemView.findViewById(R.id.tv_link)
val niceDate:TextView=itemView.findViewById(R.id.tv_link)
val title:TextView=itemView.findViewById(R.id.tv_title)
val zan:TextView=itemView.findViewById(R.id.tv_zan)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {//创建ViewHolder
var itemView :View = LayoutInflater.from(parent.context).inflate(R.layout.item_layout,parent,false)//把item_layout设置为该adapter的xml布局
return ViewHolder(itemView)
}
override fun getItemCount(): Int {//返回有多少个adapter类型的数据
recyclerViewList?.let {
return it.size
}
return 0
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {//把ViewHolder中声明的控件与相对应的数据做绑定
recyclerViewList?.let {
val tempItem=it[position]
holder.author.text=tempItem.data.datas[1].author//datas后面的[1]表示是第二个adapter类型的数据
holder.chapterName.text=tempItem.data.datas[1].chapterName
holder.link.text=tempItem.data.datas[1].link
holder.niceDate.text=tempItem.data.datas[1].niceDate
holder.title.text=tempItem.data.datas[1].title
holder.zan.text=tempItem.data.datas[0].zan.toString()
}
}
}
## ADA_RecyclerItem.kt的xml文件(item_layout.xml)
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:background="@android:color/white">
<!--data节点下一个variable节点代表一个变量,
name属性根据需要自己取名,type为需要用到的Model的全路径,
功能相当于写代码的时候引入一个类的功能-->
<data>
<variable
name="dataBean"
type="com.example.finalrecycler.DataX" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingRight="15dp">
<FrameLayout
android:id="@+id/ll_rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true">
<TextView
android:id="@+id/tv_rank_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_marginRight="5dp"
android:textColor="#2E3439"
android:textSize="12sp"
android:textStyle="bold"
android:layout_marginStart="3dp"
android:layout_marginEnd="5dp" />
</FrameLayout>
<RelativeLayout
android:id="@+id/Databean"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="false"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="0dp"
android:orientation="vertical">
<TextView
android:id="@+id/tv_authorname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_gravity="center_vertical"
android:text="作者:"
android:textColor="#666666"
android:textSize="30sp" />
<TextView
android:id="@+id/tv_author"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center_vertical"
android:text="@{dataBean.author}"
android:textColor="#666666"
android:textSize="30sp"
android:layout_alignTop="@id/tv_authorname"
android:layout_alignBottom="@id/tv_authorname"
android:layout_toEndOf="@id/tv_authorname"
android:layout_toRightOf="@id/tv_authorname" />
<TextView
android:id="@+id/tv_chapterName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_authorname"
android:layout_alignLeft="@id/tv_authorname"
android:layout_gravity="center_vertical"
android:layout_marginTop="10dp"
android:layout_toEndOf="@id/tv_author"
android:layout_toRightOf="@id/tv_author"
android:text="章节:"
android:textColor="#666666"
android:textSize="30sp" />
<TextView
android:id="@+id/tv_chapter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginBottom="6dp"
android:layout_below="@id/tv_author"
android:layout_marginTop="10dp"
android:layout_toEndOf="@id/tv_chapterName"
android:layout_toRightOf="@id/tv_author"
android:text="@{dataBean.chapterName}"
android:textColor="#666666"
android:layout_alignTop="@id/tv_chapterName"
android:layout_alignBottom="@id/tv_chapterName"
android:textSize="30sp" />
<TextView
android:id="@+id/tv_linkname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_gravity="center_vertical"
android:layout_marginBottom="6dp"
android:text="连接名字:"
android:textColor="#666666"
android:textSize="30sp"
android:layout_below="@id/tv_chapterName"
android:layout_marginTop="10dp"
/>
<TextView
android:id="@+id/tv_link"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_chapter"
android:layout_toRightOf="@id/tv_linkname"
android:layout_alignTop="@id/tv_linkname"
android:layout_alignBottom="@id/tv_linkname"
android:layout_gravity="center_vertical"
android:layout_marginBottom="6dp"
android:layout_marginTop="10dp"
android:text="@{dataBean.link}"
android:textColor="#666666"
android:textSize="30sp" />
<TextView
android:id="@+id/tv_titlename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_linkname"
android:layout_gravity="center_vertical"
android:layout_marginBottom="6dp"
android:text="标题名字:"
android:textColor="#666666"
android:textSize="30sp" />
<TextView
android:id="@+id/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_link"
android:layout_toRightOf="@id/tv_titlename"
android:layout_alignTop="@id/tv_titlename"
android:layout_alignBottom="@id/tv_titlename"
android:layout_marginTop="10dp"
android:layout_gravity="center_vertical"
android:layout_marginBottom="6dp"
android:text="@{dataBean.title}"
android:textColor="#666666"
android:textSize="30sp" />
<TextView
android:id="@+id/tv_zanname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginBottom="6dp"
android:layout_alignParentTop="true"
android:layout_toEndOf="@id/tv_author"
android:layout_toRightOf="@id/tv_author"
android:layout_marginLeft="30dp"
android:text="赞数:"
android:textColor="#666666"
android:textSize="30sp" />
<TextView
android:id="@+id/tv_zan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignBottom="@id/tv_zanname"
android:layout_gravity="center_vertical"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_marginBottom="6dp"
android:layout_toEndOf="@id/tv_zanname"
android:layout_toRightOf="@id/tv_zanname"
android:text="@{dataBean.zan}"
android:textColor="#666666"
android:textSize="30sp" />
<TextView
android:id="@+id/tv_niceDatename"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_zanname"
android:layout_gravity="center_vertical"
android:layout_marginBottom="6dp"
android:layout_alignStart="@id/tv_zanname"
android:layout_alignLeft="@id/tv_zanname"
android:layout_alignTop="@id/tv_chapterName"
android:layout_alignBottom="@id/tv_chapterName"
android:layout_toRightOf="@id/tv_link"
android:text="数据名字:"
android:textColor="#666666"
android:textSize="30sp" />
<TextView
android:id="@+id/tv_niceDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv_zan"
android:layout_gravity="center_vertical"
android:layout_toEndOf="@id/tv_niceDatename"
android:layout_alignTop="@id/tv_niceDatename"
android:layout_alignBottom="@id/tv_niceDatename"
android:layout_marginTop="10dp"
android:layout_toRightOf="@id/tv_niceDatename"
android:text="@{dataBean.niceDate}"
android:textColor="#666666"
android:textSize="30sp" />
</RelativeLayout>
</RelativeLayout>
</layout>
以上便是所有,希望帮到大家。
标签:xml,Handle,val,kotlin,fun,kt,OKhttp,import,android 来源: https://blog.csdn.net/weixin_47037778/article/details/114596821