Kotlin

作者: 嘿_叫我小王 | 来源:发表于2019-11-18 09:08 被阅读0次
    我们一直用JAVA写代码,现在学了Kotlin,怎么用Kotlin怎么进行MVP抽取呢?

    直接上代码!

    各种base类

    //BaseCallBack
    abstract class BaseCallBack<T> : ClassCallBack<T>() {
        abstract fun onSuccess(t: T)
        abstract fun OnFail(error: String)
    }
    
    //BaseView
    interface BaseView{}
    
    //BasePresenter
    interface BasePresenter{
        fun onAttch(baseview: BaseView)
    }
    

    Contrct策略类

    interface MyContract {
        //P层接口
        interface IMyPresenter : BasePresenter {
            fun getData()
        }
        //M层接口
        interface IMyModel {
            fun <T> getData(url: String, baseCallBack: BaseCallBack<T>) {}
        }
        //V层接口
        interface IMyView : BaseView {
            fun <T> onSuccess(t: T) {}
            fun OnFail(error: String) {}
        }
    }
    

    api类

    interface MyService {
        @GET
        fun get(@Url url:String): Flowable<ResponseBody>
    }
    

    重要类-----帮助获取实际泛型参数

    abstract class ClassCallBack<T> {
        val classReal: Class<T>
            get() = getSuperClassGenericType(javaClass) as Class<T>
    
        private fun getSuperClassGenericType(clz: Class<*>): Class<*> {
            val type = clz.genericSuperclass as? ParameterizedType ?: return Any::class.java
            val params = type.actualTypeArguments
            return if (params[0] is ParameterizedType) {
                (params[0] as ParameterizedType).rawType as Class<*>
            } else
                try {
                    params[0] as Class<*>
                } catch (O_O: Exception) {
                    Any::class.java
                }
        }
    }
    

    Retrofit工具类以及INetwork

    class RetrofitUtlis : INetWork {
        var myService: MyService
    
        //单例模式
        //1私有静态变量
        // 3静态方法获得本类对象
        //1和3合体
        companion object {
            private var mRetrofitUtlis: RetrofitUtlis? = null;
    
            //getInstance方法
            fun getInstance(): RetrofitUtlis? {
                if (mRetrofitUtlis == null) {
                    synchronized(RetrofitUtlis::class) {
                        //反射
                        if (mRetrofitUtlis == null) {
                            mRetrofitUtlis = RetrofitUtlis()
                        }
                    }
                }
                return mRetrofitUtlis
            }
        }
    
        //2私有无参构造
        private constructor() {
            //创建okhttp
            val okHttpClient = OkHttpClient()
                .newBuilder()
                .callTimeout(1000 * 10, TimeUnit.MILLISECONDS)
                .build()
    
    
            //创建retrofit
            //创建对象
            val retrofit = Retrofit.Builder()
                .client(okHttpClient)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .baseUrl("https://www.wanandroid.com/")
                .build()
    
            //创建接口对象
            myService = retrofit.create(MyService::class.java)
            //调用接口方法
    
        }
    
        override fun <T> get(url: String, baseCallBack: BaseCallBack<T>) {
            val flowable = myService.get(url)
    
            flowable.subscribeOn(Schedulers.io())
                .onBackpressureBuffer()//设置被观察者的缓存策略--如果大于128个事件,则继续缓存
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Subscriber<ResponseBody> {
                    override fun onComplete() {
                    }
    
                    override fun onSubscribe(s: Subscription?) {
                        s!!.request(100)
                    }
    
                    override fun onNext(t: ResponseBody?) {
                        //成功
                        val json = t?.string()
    
                        val gson = Gson()
                        val o = gson.fromJson(json, baseCallBack.classReal)
    
                        baseCallBack.onSuccess(o)
    
                    }
    
                    override fun onError(t: Throwable?) {
    
                        baseCallBack.OnFail(t.toString())
                    }
    
                });
        }
    
        override fun <T> get(url: String, map: Map<String, String>, callBack: BaseCallBack<T>) {}
    
        override fun <T> post(url: String, callBack: BaseCallBack<T>) {}
    
        override fun <T> post(url: String, map: Map<String, String>, callBack: BaseCallBack<T>) {}
    }
    
    interface INetWork{
        fun <T> get(url: String, baseCallBack: BaseCallBack<T>)
    
        fun <T> get(url: String, map: Map<String, String>, callBack: BaseCallBack<T>)
        fun <T> post(url: String, callBack: BaseCallBack<T>)
        fun <T> post(url: String, map: Map<String, String>, callBack: BaseCallBack<T>)
    }
    

    M层实现类

    class MyModel : MyContract.IMyModel {
        override fun <T> getData(url: String, baseCallBack: BaseCallBack<T>) {
            RetrofitUtlis.getInstance()?.get(url, baseCallBack)
        }
    }
    

    P层实现类

    class MyPresenter : MyContract.IMyPresenter {
        var myModel: MyContract.IMyModel
        lateinit var myView: MyContract.IMyView
    
        constructor() {
            myModel = MyModel()
        }
    
        override fun getData() {
            myModel.getData("https://www.wanandroid.com/project/list/1/json?cid=294", object : BaseCallBack<MyBean>() {
                override fun onSuccess(t: MyBean) {
                    myView.onSuccess(t)
                }
    
                override fun OnFail(error: String) {
                    myView.OnFail(error)
                }
            })
        }
    
        override fun onAttch(baseview: BaseView) {
            myView = baseview as MyContract.IMyView;
        }
    
    }
    

    那么kotlin写RecyclerView呢?

    学习网址
    主要是适配器方面

    首先介绍一下单布局(以及对条目的监听)

    class SAdapter(private val context: Context, private val list: ArrayList<DataX>?) :
        RecyclerView.Adapter<SAdapter.SimpleViewHolder>() {
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SAdapter.SimpleViewHolder {
            var view = LayoutInflater.from(context).inflate(R.layout.item_view, null)
            return SimpleViewHolder(view)
        }
    
        override fun getItemCount(): Int {
            return list!!.size;
        }
    
        override fun onBindViewHolder(holder: SAdapter.SimpleViewHolder, position: Int) {
            holder.tv_re.setText(list!!.get(position).desc)
    
    //对条目进行监听
       holder.tv_re.setOnClickListener {
                Toast.makeText(context, holder.tv_re.text, Toast.LENGTH_SHORT).show();
            }
        }
    
    
        inner class SimpleViewHolder(view: View) : RecyclerView.ViewHolder(view) {
            var tv_re: TextView = view.findViewById(R.id.tv_re_item)
        }
    
    }
    

    接下来介绍一下多布局吧(包括条目点击和接口回调)

    class SAdapter(private val context: Context, private val list: ArrayList<DataX>?) :
        RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    
        var myInterface: MyInterface? = null
        fun setListener(myInterface: MyInterface?) {
            this.myInterface = myInterface
        }
    
    
        private val VIEW_0 = 0
        private val VIEW_1 = 1
        private val VIEW_2 = 2
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            var view: View
            if (viewType == 0) {
                view = LayoutInflater.from(context).inflate(com.whx.kotlino.R.layout.item_view, null)
                return ViewHolder0(view)
            } else if (viewType == 1) {
                view = LayoutInflater.from(context).inflate(com.whx.kotlino.R.layout.item_view1, null)
                return ViewHolder1(view)
            } else {
                view = LayoutInflater.from(context).inflate(com.whx.kotlino.R.layout.item_view2, null)
                return ViewHolder2(view)
            }
        }
    
        override fun getItemCount(): Int {
            return list!!.size;
        }
    
        override fun getItemViewType(position: Int): Int {
            if (position == VIEW_0) {
                return 0
            } else if (position == VIEW_1) {
                return 1
            } else {
                return 2
            }
        }
    
        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            val type = getItemViewType(position)
            if (type == 0) {
                if (holder is ViewHolder0) {
                    holder.tv_re.setText(list!!.get(position).desc)
                    holder.tv_re.setOnClickListener {
                        if (myInterface != null) {
                            myInterface!!.test(position)
                        }
                    }
                }
            } else if (type == 1) {
                if (holder is ViewHolder1) {
                    Glide.with(context).load("https://wanandroid.com/blogimgs/2baa4b4b-acfe-473c-b534-9d672423e564.png")
                        .into(holder.iv_view1)
                }
            } else {
                if (holder is ViewHolder2) {
                    //设置图片加载器
                    holder.banner_item2.setImageLoader(GlideImage())
                    //加载网络图片
                    val mImages = ArrayList<String>()
                    mImages.add("https://wanandroid.com/blogimgs/2baa4b4b-acfe-473c-b534-9d672423e564.png")
                    mImages.add("https://wanandroid.com/blogimgs/2baa4b4b-acfe-473c-b534-9d672423e564.png")
                    mImages.add("https://wanandroid.com/blogimgs/2baa4b4b-acfe-473c-b534-9d672423e564.png")
                    //设置图片集合
                    holder.banner_item2.setImages(mImages)
    
                    //banner设置方法全部调用完毕时最后调用
                    holder.banner_item2.start()
                }
    
            }
        }
    
        inner class GlideImage : ImageLoader() {
            override fun displayImage(context: Context, path: Any, imageView: ImageView) {
                Glide.with(context).load(path).into(imageView)
            }
        }
    
        class ViewHolder0(view: View?) : RecyclerView.ViewHolder(view!!) {
            var tv_re: TextView = view!!.findViewById(com.whx.kotlino.R.id.tv_re_item)
        }
    
        class ViewHolder1(view: View?) : RecyclerView.ViewHolder(view!!) {
            var iv_view1: ImageView = view!!.findViewById(com.whx.kotlino.R.id.iv_view1)
        }
    
        class ViewHolder2(view: View?) : RecyclerView.ViewHolder(view!!) {
            var banner_item2: Banner = view!!.findViewById(com.whx.kotlino.R.id.banner_item2)
        }
    
        interface MyInterface {
            fun test(position: Int)
        }
    
    }
    

    接下来我们来谈一谈数据库吧!

    参考网址
    首先先配置

    //GreenDao
    //项目app依赖
    implementation 'org.greenrobot:greendao:3.2.2' // add library
    -------------------------
    //工程依赖
     mavenCentral() // 添加的代码
     classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
    -------------------------
    //项目依赖
    apply plugin: 'org.greenrobot.greendao' // apply plugin
    -------------------------
    greendao{
            schemaVersion 1 //数据库版本号
            daoPackage 'com.example.exercise2.dao'  //数据库全路径
            targetGenDir 'src/main/java'  //存放位置
        }
    

    然后创建一个bean类(用java类创建)

    @Entity
    public class MyDaoBean {
        //自增的ID
        @Id(autoincrement = true)
        long e_id;
        String name;
    }
    

    锤后自动生成三个类 路径是根据你上边 greendao 给的

    接下来我们写工具类

    class My private constructor(context: Context) {
        var myDaoDao: MyDaoBeanDao
    
        init {
            //第一种方法
            val devOpenHelper = DaoMaster.DevOpenHelper(context, "my", null)
            val writableDb = devOpenHelper.writableDb
            val daoMaster = DaoMaster(writableDb)
            val newSession = daoMaster.newSession()
            this.myDaoDao = newSession.myDaoBeanDao
            //第二种方法
    //        val newDevSession = DaoMaster.newDevSession(context, "my")
    //        val myDaoDao1 = newDevSession.myDaoDao
        }
    
        //伴生  ——   单例
        companion object {
            private var my: My? = null
            fun getmy(context: Context): My? {
                if (my == null) {
                    @Synchronized
                    if (my == null) {
                        my = My(context)
                    }
                }
                return my
            }
        }
    
    
        //添加数据
        fun getinsert(myDao: MyDaoBean) {
            myDaoDao.insert(myDao)
        }
    
        //删除数据
        fun getdelet(myDao: MyDaoBean) {
            myDaoDao.delete(myDao)
        }
    
        //修改数据
        fun getupdata(myDao: MyDaoBean) {
            myDaoDao.update(myDao)
        }
    
        //查询数据(指定数据)
        fun getquest_count(name: String): List<MyDaoBean> {
            val where = myDaoDao.queryBuilder().where(MyDaoBeanDao.Properties.Name.eq(name)).list()
            return where
        }
    
        //查询数据(所有数据)
        fun getquest_true(name: String): List<MyDaoBean> {
            val list = myDaoDao.queryBuilder().list()
            return list
        }
    
        //查询数据(模糊数据)
        fun getquest_like(name: String): List<MyDaoBean> {
            val where = myDaoDao.queryBuilder().where(MyDaoBeanDao.Properties.Name.like("%$name%")).list()
            return where
        }
    }
    

    调用--添加数据

    My.getmy(this)?.getinsert(myDaoBean)
    

    相关文章

      网友评论

          本文标题:Kotlin

          本文链接:https://www.haomeiwen.com/subject/piivvctx.html