Kotlin使用retrofit实现recyclerview

来源:互联网 发布:php eval 解密 编辑:程序博客网 时间:2024/06/05 19:39

使用kotlin新语言在as里面实现recyclerview


使用as 创建一个project工程,要勾选这里,支持kotlin

需要安装一个插件,安装完重启as,这个插件用来生成数据类data


重启as后,开始导入依赖,这里使用到了retrofit,Rxjava,glide,recyclerview

implementation 'com.android.support:recyclerview-v7:27.0.2'    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'    compile 'io.reactivex.rxjava2:rxjava:2.1.7'    compile 'com.squareup.retrofit2:retrofit:2.3.0'    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'    compile 'com.squareup.retrofit2:converter-gson:2.3.0'    implementation 'com.github.bumptech.glide:glide:3.8.0'    implementation 'com.android.support:support-v4:27.0.2'//glide需要v4支持
请求的接口:retrofit请求的接口

http://japi.juhe.cn/comic/book?key=f54c4c57143b8fad9bf3193cab52a81c

清单文件中加入权限

  <uses-permission android:name="android.permission.INTERNET"/>

创建一个kotlin class  类Bean


快捷键alt+insert 选择Covert Json into kotlin class生成数据类data class Bean

    //数据类  alt+insertdata class Bean(val error_code: Int, //200val reason: String, //请求成功!val result: Result)data class Result(val total: Int, //15767val limit: Int, //20val bookList: List<Book>)data class Book(val name: String, //灵神考试val type: String, //少年漫画val area: String, //国漫val des: String,val finish: Boolean, //falseval lastUpdate: Int, //20150603val coverImg: String //http://imgs.juheapi.com/comic_xin/5559b86938f275fd560ad613.jpg)

创建retrofit请求网络的接口类,同样是kotlin class

interface IService {    //http://japi.juhe.cn/comic/book?key=f54c4c57143b8fad9bf3193cab52a81c    @GET("/comic/book?key=f54c4c57143b8fad9bf3193cab52a81c")    fun getData() : Observable<ResponseBody>}
activity_main的布局,一个recyclerview

<LinearLayout 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:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.example.menglucywhh.kotlindemo.MainActivity">   <android.support.v7.widget.RecyclerView       android:id="@+id/recyclerview"       android:layout_width="match_parent"       android:layout_height="match_parent"/></LinearLayout>
recy_layout.xml的布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <ImageView        android:layout_width="160dp"        android:layout_height="160dp"        android:id="@+id/item_imageview"/>    <TextView        android:textSize="23sp"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/item_textview"        android:textColor="#FF0000"/></LinearLayout>
MainActivity.kt的代码,创建出适配器对象,写请求网络的方法并调用,将返回的数据添加到适配器里

import android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.support.v7.widget.LinearLayoutManagerimport android.widget.LinearLayoutimport com.google.gson.Gsonimport io.reactivex.android.schedulers.AndroidSchedulersimport io.reactivex.schedulers.Schedulersimport kotlinx.android.synthetic.main.activity_main.*import retrofit2.Retrofitimport retrofit2.adapter.rxjava2.RxJava2CallAdapterFactoryclass MainActivity : AppCompatActivity() {    lateinit var adapter : IAdapter    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)        //不需要找控件 直接使用id        //recyclerview.layoutManager = 在等号左面表示 set方法,设置布局管理器        recyclerview.layoutManager = LinearLayoutManager(this,LinearLayout.VERTICAL,false)        //创建适配器对象        adapter = IAdapter(this)        //设置recyclerview的适配器,,等号左面是set        recyclerview.adapter = adapter        //请求网络数据的方法        getData()    }    fun getData(){        //http://japi.juhe.cn/comic/book?key=f54c4c57143b8fad9bf3193cab52a81c        //创建retrofit对象        var retrofit = Retrofit.Builder()                .baseUrl("http://japi.juhe.cn")                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())                .build();        //创建 请求数据的接口实体类        var iservice : IService = retrofit.create(IService::class.java)        iservice.getData()                .subscribeOn(Schedulers.io())                .observeOn(AndroidSchedulers.mainThread())                .subscribe({                    //这里用了lambda表达式                    next ->//onnext                    //onnext方法的参数是 请求返回的结果,string字符串                    var result = next.string()                    print(result)                    var  gson = Gson()                    var bean = gson.fromJson(result,Bean::class.java)//解析                    adapter.addData(bean)                },{                    t ->  //onerror                },{                    //oncomplete没有参数                },{                    d->//subscribeon//                    d.dispose()                })    }}
IAdapter.kt 适配器的代码,新建kotlin class

import android.content.Contextimport android.support.v7.widget.RecyclerViewimport android.view.Viewimport android.view.ViewGroupimport android.widget.ImageViewimport android.widget.TextViewimport com.bumptech.glide.Glideclass IAdapter(context1 : Context) : RecyclerView.Adapter<IAdapter.IViewHolder>() {    var context:Context = context1    var list : ArrayList<Book> = ArrayList()    fun addData(bean : Bean){        list.addAll(bean.result.bookList)        notifyDataSetChanged()    }    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): IViewHolder {        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.    var view = View.inflate(context,R.layout.recy_layout,null)        return IViewHolder(view)    }    override fun onBindViewHolder(holder: IViewHolder?, position: Int) {       // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.      //设置控件显示        holder!!.item_textview.setText(list.get(position).name)        Glide.with(context).load(list.get(position).coverImg).into(holder!!.item_imageview)    }    override fun getItemCount(): Int {       // TODO("not implemented") //To change body of created functions use File | Settings | File Templates.        return list.size    }    class IViewHolder(view : View) : RecyclerView.ViewHolder(view){        lateinit var item_imageview : ImageView        lateinit var item_textview : TextView        init{            item_imageview = view.findViewById(R.id.item_imageview)            item_textview = view.findViewById(R.id.item_textview)        }     /*   constructor(view: View) : super(view){            item_imageview = view.findViewById(R.id.item_imageview)            item_textview = view.findViewById(R.id.item_textview)        }*/    }}







阅读全文
1 0
原创粉丝点击