Kotlin Anko Layout+MVP(Glide,Retrofit,OkHttp,RxJava)开发Android运用程序

Kotlin编程开发Android运用程序的相关介绍


image

介绍

Anko是一个Kotlin库,使Android运用程序开发更快更容易,代码整洁,易于阅读,且让你忘记Android SDKfor Java的粗糙边缘。

Anko库中包含的子库

  • Anko Commons : 一个轻量级的库,包含intent,dialogs,logging等的帮助。

  • Anko Layouts :一种快速和类型安全的方式来编写动态的Android布局

  • Anko SQLite :用于Android SQLite的查询DSL和解析后的集合。

  • Anko Coroutines :基于kotlinx.corountines库的实用程序。


这里,使用的是Anko Lyouat v0.10.0版本

分析项目

案例中页面图

这里写图片描述

实现UI的过程分析:使用Anko-Layout实现

  • 最外层用Activity,写一个RelativeLayout作为根布局,用于添加Fragment。
  • Framgent的根布局包裹一个标题的TextView,和一个滚动视图的RecyclerView。
  • 滚动视图中item是用一个布局包裹一个ImageView和一个TextView.

业务模块分析

  • 使用MVP架构为项目分离关注点。
  • Retrofit+OkHttp作为网络异步框架
  • RxJava+RxAndroid作为响应式框架
  • Glide作为图片异步加载框架

在Gradle配置依赖库

根据上面的分析 ,在项目的Gradle中 添加相关的Anko Layout包和相关业务依赖包:AndroidStudio2.2-2.3配置Anko插件

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    // 添加Anko Layouts,根据当前sdk来决定版本号
    compile 'org.jetbrains.anko:anko-sdk25:0.10.0'
    compile 'org.jetbrains.anko:anko-appcompat-v7:0.10.0'
    // 添加协调 listeners for Anko Layouts
    compile 'org.jetbrains.anko:anko-sdk25-coroutines:0.10.0'
    compile 'org.jetbrains.anko:anko-appcompat-v7-coroutines:0.10.0'
    // RecyclerView-v7
    compile 'org.jetbrains.anko:anko-recyclerview-v7:0.10.0'
    compile 'org.jetbrains.anko:anko-recyclerview-v7-coroutines:0.10.0'
    compile 'com.android.support:recyclerview-v7:25.3.1'


    //Glide v4
    compile 'com.github.bumptech.glide:glide:4.0.0-RC0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.0.0-RC0'
    //Retrofit 2.x
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    //OkHttp 3.x
    compile 'com.squareup.okhttp3:okhttp:3.8.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.8.0'
    //RxJava 1.x
    compile 'io.reactivex:rxjava:1.3.0'
    compile 'io.reactivex:rxandroid:1.2.1'
}

开始编写代码

1. 在Activity中编写一个RelativeLayout:

这里使用AnkoComponent接口,来创建DSL的UI。

class MovieListActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //Anko Component接口的扩展方法setContentView()
        ActivityUI().setContentView(this)
        .........
    }
}
/**
 * 使用AnkoComponent作为
 */
class ActivityUI : AnkoComponent<MainActivity> {
    override fun createView(ui: AnkoContext<MainActivity>) = with(ui) {
        relativeLayout{//RelativeLayout作为根布局
           id= ViewID.CONTENT_LAYOUT//设置id,方便添加Fragment
        }
    }
}
2.在Fragment中编写一个标题和一个滚动视图

在Fragment的onCreateView()中使用UI { ... }.view来构建Layout DSL。一个竖直方向的Linearlayout包裹一个TextView和RecyclerView。

class MovieListFragment : Fragment(), MovieListConstract.View {

   lateinit var recyclerView: RecyclerView
   lateinit var rootView :View

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
       rootView = UI {
            verticalLayout {
                lparams(width= matchParent,height = matchParent)//设置布局的宽高
                textView(R.string.title) {//设置tile
                    textSize = 18f//字体大小
                    paint.isFakeBoldText = true//设置粗体
                    gravity = Gravity.CENTER_HORIZONTAL//控件中字体水平居中
                    verticalPadding = dip(10) //控件的上下Padding值
                    textColor=Color.WHITE//字体颜色
                    backgroundResource = R.color.colorPrimaryDark//控件的背景
                }.lparams(width = matchParent, height = wrapContent)//控件的宽高
                recyclerView {//设置滚动视图RecyclerView
                    id = ViewID.RECYCLERVIEW_ID//控件的id
                }.lparams(width = matchParent, height = matchParent)//控件的宽高
            }
        }.view
        // 根据id获取指定控件
        recyclerView = rootView.findViewById(ViewID.RECYCLERVIEW_ID) as RecyclerView 
        return rootView
    }

    ......//省略部分代码

    companion object {
        val instance = MovieListFragment()
        val TAG = MovieListFragment::class.java.simpleName
    }
}

然后在Activity添加Framgent:

class MovieListActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityUI().setContentView(this)//Anko Component接口的扩展方法setContentView()

        var view=MovieListFragment.instance
        MovieListPresenter(view)
        supportFragmentManager.beginTransaction().add(ViewID.CONTENT_LAYOUT, view, MovieListFragment.TAG).commit()
    }
}
3. 编写RecyclerView中的item:

使用AnkoComponent来构建item的UI.一个水平方向的LinearLayout包裹一个ImageView和一个TextView。

class MovieListAdapter(val context: Context,var list: List<MovieList.Movie>) : RecyclerView.Adapter<MovieListAdapter.ViewHolder>() {
    /**
     * 重复使用的Context添加多个view.
     */
    private val ankoContext = AnkoContext.createReusable(context, this)

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
        return ViewHolder(MovieListAdapterUI().createView(ankoContext))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        GlideUtils.loadUrlImage(context,list[position].images.large,holder.imageView)
        holder.title_Tv.text=list[position].title
    }

    override fun getItemCount() = list.size
    /**
     * 自定义ViewHolder
     */
    inner class ViewHolder(rootView: View) : RecyclerView.ViewHolder(rootView) {
         val  imageView=rootView.findViewById(ViewID.IMAGEVIEW_ID) as ImageView
         val  title_Tv=rootView.findViewById(ViewID.TITLE_ID) as TextView
    }
}

/**
 * 使用AnkoComponent来构建item的UI
 */
class MovieListAdapterUI : AnkoComponent<MovieListAdapter> {
    override fun createView(ui: AnkoContext<MovieListAdapter>) = with(ui) {
        linearLayout {
            padding = dip(10)//设置padding
            imageView {
                id = ViewID.IMAGEVIEW_ID//设置id
                scaleType = ImageView.ScaleType.CENTER_CROP//图片中心裁剪
            }.lparams(width = dip(60), height = dip(60))//设置图片的宽高
            textView {
                id = ViewID.TITLE_ID//设置id
                textSize = 14f//字体大小
                paint.isFakeBoldText = true//粗体
            }.lparams {
                leftMargin = dip(10)//左边偏移量
                gravity = Gravity.CENTER_VERTICAL//竖直居中
            }
        }
    }
}

然后将Adapter添加到RecyclerView中:

   /**
     * 加载数据
     */
override fun loadMovie(list: List<MovieList.Movie>) {
        recyclerView .layoutManager = LinearLayoutManager(activity)
        recyclerView.adapter = MovieListAdapter(activity, list)
}
4.考虑到控件的Id管理,编写了一个类
class ViewID{
    /**
     * 定义常量的控件ID
     */
    companion object{
        const  val IMAGEVIEW_ID=1//图片的id
        const  val TITLE_ID=2//页面中标题的id
        const  val RECYCLERVIEW_ID=3//页面中滚动视图的id
        const  val CONTENT_LAYOUT=4//页面中容器的id
    }
}
5. 编写电影列表的业务实现:

如何使用MVP架构,如何使用Glide ,Retrofit,OkHttp,RxJava,在上篇已经详细介绍了。这里就不在介绍,请阅读Kotlin 编写Android MVP项目(RxJava+Rerotfit+OkHttp+Glide)

项目最终结构图:

这里写图片描述

6. 效果图展示:

这里写图片描述

7. 本项目的代码https://github.com/13767004362/KotlinAnkoLayoutProject

资源参考

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值