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

  • Kotlin编程之AndroidStudio(包括3.0与2.x版本)配置与使用
  • Kotlin编程开发Android运用程序(Volley+Gson依赖库)
  • Kotlin编程之Kotlin Android Extensions(扩展插件)
  • Kotlin编程之Glide v4 Generated API(Unresolved reference GlideApp)
  • Kotlin Android Extensions+Android MVP项目(RxJava+Rerotfit+OkHttp+Glide)
  • AndroidStudio2.2-2.3配置Anko插件

Kotlin Anko Layout+MVP(Glide,Retrofit,OkHttp,RxJava)开发Android运用程序_第1张图片

介绍

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版本

分析项目

案例中页面图

Kotlin Anko Layout+MVP(Glide,Retrofit,OkHttp,RxJava)开发Android运用程序_第2张图片

实现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 {    override fun createView(ui: AnkoContext) = 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) : RecyclerView.Adapter() {    /**     * 重复使用的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 {    override fun createView(ui: AnkoContext) = 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) {        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)。

项目最终结构图:

Kotlin Anko Layout+MVP(Glide,Retrofit,OkHttp,RxJava)开发Android运用程序_第3张图片

6. 效果图展示:

Kotlin Anko Layout+MVP(Glide,Retrofit,OkHttp,RxJava)开发Android运用程序_第4张图片

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


资源参考

  • Anko库:https://github.com/Kotlin/anko

更多相关文章

  1. Android -- 设置textview文字居中或者控件居中
  2. 系出名门Android(7) - 控件(View)之ZoomControls, Include, Vide
  3. Android界面布局基本知识简述
  4. 2.3.2EditText控件
  5. Android 开关控件Switch使用
  6. Android布局属性解析
  7. android ListView控件 去上下滑动阴影 选中背景黄色
  8. android 布局文件属性说明
  9. Android 下控件位置大小调整

随机推荐

  1. 7.1.3 TimePicker结合案例详解
  2. Android用户和用户组的定义
  3. Android 源码下载遇到 403错误 的解决办
  4. Android判断程序是否第一次启动
  5. Android XMPP 即时通讯
  6. Android裁剪图像实现方法示例
  7. Android自动测试代码
  8. 关于android软键盘隐藏总结
  9. Android学习笔记(八)之Android 读写xml文
  10. php获取手机设备信息