8.kotlin安卓实践课程-用kotlin写第一个fragment


简介

主要会通过安卓实战来讲解kotlin语法和实际应用,本教程设及知识点包括框架模式mvp+mvvm, Databinding(数据绑定框架),Dagger2(依赖注入框架),DeepLink(页面路由框架),Rxjava,RxAndroid(异步操作框架),Retrofit,Okhtttp等,不过本教程重点在kotlin所以这些框架需要了解可自行百度。

针对人群:Android中级以上,kotlin入门


我们马上开始完成第一个kotlin代码实现的fragment


首先先看一下代码

/**
 *
 * Created by bigman on 18-05-18.
 */
class AndroidFragment : BaseBingingFragment<ViewRecyclerBinding>(), AndroidContract.View {

    private var mList = ArrayList<AndroidBean>()

    private lateinit var mAdapter: AndroidAdapter

    private var mPage = 1

    @Inject lateinit var mPresenter: AndroidPresenter

    override fun createDataBinding(inflater: LayoutInflater?, container: ViewGroup?,
                                   savedInstanceState: Bundle?): ViewRecyclerBinding {
        return ViewRecyclerBinding.inflate(inflater!!, container, false)
    }

    override fun initView() {
        mAdapter = AndroidAdapter(mList)
        context.getMainComponent().plus(AndroidModule(this)).inject(this)

        with(mBinding) {
            recyclerView.adapter = mAdapter
            recyclerView.layoutManager = LinearLayoutManager(context)

            recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    //是否滚动到底部
                    if (!recyclerView?.canScrollVertically(1)!!) {
                        mPresenter.getData(++mPage, ANDROID)
                    }
                }

                override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                }
            })
        }

        //请求数据
        mPresenter.getData(mPage, ANDROID)

        mAdapter.setOnItemClickListener {
            pos ->
            val url = URLEncoder.encode(mList[pos].url)
            GankRouter.router(context, GankClientUri.DETAIL + url)
        }


    }

    override fun setData(results: List<AndroidBean>) {
        mList.addAll(results)
        mAdapter.notifyDataSetChanged()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.unSubscribe()
    }

    companion object {
        val ANDROID = "ANDROID"
        fun newInstance(): AndroidFragment {
            val fragment = AndroidFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }

}

AndroidFragment 代码结构其实和MainActivity的差不多,首先是两个主要方法createDataBindinginitView,他同样是基类声明的两个抽象方法,我们看看基类 BaseBingingFragment的代码:

/**
 * Created by bigman on 18-05-17.
 */
abstract class BaseBingingFragment<B:ViewDataBinding> : Fragment(){
     lateinit var mBinding : B
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        mBinding = createDataBinding(inflater,container,savedInstanceState)
        initView()
        return mBinding.root

    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

    abstract fun  createDataBinding(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): B

    abstract fun initView()

}

当然它的实现和activity的基类一样,就是实现了databinding框架的页面绑定,不记得的同学可以翻看一下前面,我们再看基类提供的抽象方法的具体实现

override fun createDataBinding(inflater: LayoutInflater?, container: ViewGroup?,
                                   savedInstanceState: Bundle?): ViewRecyclerBinding {
        return ViewRecyclerBinding.inflate(inflater!!, container, false)
 }

这里就是把view_recycler.xml由Databinding自动生成类ViewRecyclerBinding和页面绑定起来

然后再看看initView方法实现代码

 override fun initView() {
        mAdapter = AndroidAdapter(mList)
        context.getMainComponent().plus(AndroidModule(this)).inject(this)

        with(mBinding) {
            recyclerView.adapter = mAdapter
            recyclerView.layoutManager = LinearLayoutManager(context)

            recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    //是否滚动到底部
                    if (!recyclerView?.canScrollVertically(1)!!) {
                        mPresenter.getData(++mPage, ANDROID)
                    }
                }

                override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                }
            })
        }

        //请求数据
        mPresenter.getData(mPage, ANDROID)

        mAdapter.setOnItemClickListener {
            pos ->
            val url = URLEncoder.encode(mList[pos].url)
            GankRouter.router(context, GankClientUri.DETAIL + url)
        }


    }

首先是实例化了一个adapter适配器,然后把通过context.getMainComponent().plus(AndroidModule(this)).inject(this)实现了依赖注入,然后是通过一个with函数包含的代码块实现了 recyclerView的初始化和滚动监听

语法点: with函数
  • with函数是将某对象作为函数的参数,在函数块内可以通过 this 指代该对象。返回值为函数块的最后一行或指定return表达式。
  • 意思就是说如果要操作with的对象参数直接调用就行,不用多余的修饰符,比如这里的recyclerView就是mBinding对象的成员变量,完整写法应该是mBinding . recyclerView

剩下的需要注意这段代码

  companion object {
        val ANDROID = "ANDROID"
        fun newInstance(): AndroidFragment {
            val fragment = AndroidFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }

这个伴生对象我们前面说过,这里再说一次,它相当于java的静态成员变量,这里的代码大家可以对比一下java的写法,相信java的写法大家都很熟悉了


欢迎一起交流,有问题加群交流

kotlin实战交流群群二维码.png
上一篇:Calendar时间操作


下一篇:6.kotlin安卓实践课程-用kotlin写第一个activity对应P层