DSL In Action

DSL In Action

伴隨著Kotlin的發(fā)展,有一個神奇的框架anko-layout,一直存在于我們的視野卻又一直因為各種原因無法用于生產(chǎn)環(huán)境中。最近在寫項目時,再次拿出anko這個框架,思考它在UI小組件上的可用性。

PS: Anko != Anko_Layouts ,但是為了表述方便,文中一部分Anko是代指這Anko Layouts框架,大家自己理解一下~

概述

關(guān)于Anko-Layouts框架的好處和局限性,網(wǎng)上已經(jīng)有大部分文章在講,它好在用DSL的方式來描述View,而缺點在于無法即時預(yù)覽,在這方面導(dǎo)致Anko DSL的開發(fā)效率不及XML傳統(tǒng)方式。經(jīng)過大家的一些踩坑,以及開發(fā)上的試用,一致表示,Anko Layouts無法用在成熟的項目之中,還是老老實實用XML吧…

Anko Layouts的DSL設(shè)計那么棒… 就要這么放棄了嗎

大家眼里的Anko Layouts DSL

受官方文檔的“誘導(dǎo)”,大家對于Anko Layouts DSL的印象大概是這樣子的:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    
    verticalLayout {
        padding = dip(30)
        editText {
            hint = "Name"
            textSize = 24f
        }
        editText {
            hint = "Password"
            textSize = 24f
        }
        button("Login") {
            textSize = 26f
        }
    }
}

val name: EditText = with(ankoContext) {
    editText {
        hint = "Name"
    }
}

官方的Demo中,將Activity的布局方式從setContentView()中傳入Layout ID換到了直接的DSL,嗯… 看起來還不錯,官方文檔也提供了一個Anko View 組件化的方案:

class MyActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        MyActivityUI().setContentView(this)
    }
}

class MyActivityUI : AnkoComponent<MyActivity> {
    override fun createView(ui: AnkoContext<MyActivity>) = with(ui) {
        verticalLayout {
            val name = editText()
            button("Say Hello") {
                onClick { ctx.toast("Hello, ${name.text}!") }
            }
        }
    }
}

直戳XML的痛點,XML作為傳統(tǒng)的View構(gòu)建方式,復(fù)用的方式極其有限(比如說蛋疼的include),而Anko可以在編程語言的層面來做View組件的復(fù)用,實在是棒…

但是它背后做了啥?這些View是怎么被構(gòu)造的?這些View是怎么被添加進去的?如果是復(fù)雜的參數(shù)又應(yīng)該怎么辦?
這些問題在你計劃把Anko Layouts DSL 作為構(gòu)建View的方式后,逐個浮出水面,然后開始勸退… QAQ

Anko Layout DSL 到底在干什么

為什么我們可以用DSL來寫界面?

Kotlin DSL本身就是語法糖而已,所以DSL背后就是使用Kotlin代碼來自己初始化View,初始化LayoutParams,進行addView之類…

而其實LayoutInflater它本身也只是在做相似的事情而已,LayoutInflater是根據(jù)XML文件里面的配置來通過反射初始化View,根據(jù)其他字段來填充View屬性以及LayoutParams什么的。所以沒有什么神秘的東西…

我們梳理一下,其實在非XML代碼中構(gòu)建View的時候,無非就是 new View(context) -> addView

那么我們瞅瞅Anko的代碼,是不是也有相似的邏輯(不用想也是?。?/p>

inline fun ViewManager.textView(init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
    return ankoView(`$$Anko$Factories$Sdk25View`.TEXT_VIEW, theme = 0) { init() }
}

inline fun <T : View> ViewManager.ankoView(factory: (ctx: Context) -> T, theme: Int, init: T.() -> Unit): T {
    val ctx = AnkoInternals.wrapContextIfNeeded(AnkoInternals.getContext(this), theme)
    val view = factory(ctx)
    view.init()
    AnkoInternals.addView(this, view) // this.addView(view)
    return view
}

//自定義的View添加DSL支持的話 (ColorCircleView是我的一個自定義View)
//這里的代碼比ViewManager.textView更容易理解
inline fun ViewManager.colorCircleView() = colorCircleView {}

inline fun ViewManager.colorCircleView(init: ColorCircleView.() -> Unit): ColorCircleView {
    return ankoView({ ColorCircleView(it) }, theme = 0, init = init)
}

我們可以大概看到,在AnkoView中構(gòu)造了一個View然后通過ViewManager添加到ViewGroup里面去。
那么,ViewManager是什么呢?

package android.view;

/** Interface to let you add and remove child views to an Activity. To get an instance
  * of this class, call {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()}.
  */
public interface ViewManager
{
    public void addView(View view, ViewGroup.LayoutParams params);
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);
    public void removeView(View view);
}

所以ViewManager是管理著View的添加,修改以及刪除的接口,不出意料,ViewGroup就實現(xiàn)了ViewManager

public abstract class ViewGroup extends View implements ViewParent, ViewManager {

然后我們梳理一下,textView是一個拓展方法,拓展到了ViewManager接口里面,因此所有實現(xiàn)ViewManager接口的類都可以調(diào)用這個textView方法,而調(diào)用這個方法的結(jié)果就是把textView加入到此ViewGroup里面,比如說:

val frameLayout = findViewById<FrameLayout>(R.id.fl_container)

val view = frameLayout.textView {
    text = "辣雞辦公網(wǎng)??????????????"
    textColor = Color.BLACK
    textSize = 16f
}.apply {
    layoutParams = FrameLayout.LayoutParams(matchParent, wrapContent)
    visibility = View.GONE
}

效果就是,在FrameLayout里面添加了一個TextView,Textview擁有著DSL閉包里面的配置。

另外,我們構(gòu)造View的方式還有,傳入一個Context就可以構(gòu)建出一個View,我們可以瞅瞅相關(guān)的代碼:

inline fun Context.constraintLayout(): android.support.constraint.ConstraintLayout = constraintLayout() {}

inline fun Context.constraintLayout(init: (@AnkoViewDslMarker _ConstraintLayout).() -> Unit): android.support.constraint.ConstraintLayout {
    return ankoView(`$$Anko$Factories$ConstraintLayoutViewGroup`.CONSTRAINT_LAYOUT, theme = 0) { init() }
}

背后的實現(xiàn)我們不做深究,大概就是用Context來構(gòu)建出一個View,然后拿到了View,我們就可以為所欲為了。

怎么把Anko靈活用起來

簡單回顧一下上面一節(jié)的內(nèi)容: 如果我們擁有一個ViewGroup或者擁有一個Context,就可以用來創(chuàng)建View

因此Anko的用法遠要比你想象中的靈活 -> 可以拿到Context/ViewGroup的地方就可以使用Anko,而Anko的作用也就是簡化初始化View + AddView的流程。

舉個栗子?
舉個栗子?

比如說我已經(jīng)用XML寫好了頁面的布局,然后我們需要根據(jù)代碼在其中一個FrameLayout中動態(tài)添加一些東西。我們就可以拿到這個FrameLayout的引用,然后就可以用anko大展拳腳了。

val frameLayout = findViewById<FrameLayout>(R.id.fl_container)
val view = frameLayout.textView {
    text = "辣雞辦公網(wǎng)??????????????"
    textColor = Color.BLACK
    textSize = 16f
}.apply {
    layoutParams = FrameLayout.LayoutParams(matchParent, wrapContent)
    visibility = View.GONE
}

frameLayout.verticalLayout { 
    
}

摸著良心說,是不是比自己創(chuàng)建View(不管是從Inflater還是java code方式)都要簡單太多。

再舉一個例子,在BottomSheetDialogFragment中,我們拿到Dialog后,需要通過setContView的方式來給它設(shè)置有個View進去,而我們一般會在XML寫好然后Inflater獲得View加載進去,或者自己一個一個new。有了Anko后,你可以隨手寫起DSL。

    override fun setupDialog(dialog: Dialog?, style: Int) {
        if (dialog == null) return
        val context = dialog.context
        
        val view = context.nestedScrollView {
            verticalLayout {
                constraintLayout {
                    backgroundColor = getColorCompat(R.color.colorPrimary)

                    val titleText = textView {
                        text = "課程表設(shè)置"
                        id = View.generateViewId()
                        textSize = 20f
                        textColor = Color.WHITE
                    }.lparams(width = wrapContent, height = wrapContent) {
                        startToStart = ConstraintLayout.LayoutParams.PARENT_ID
                        topToTop = ConstraintLayout.LayoutParams.PARENT_ID
                        bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
                        margin = dip(16)
                    }

                }

                indicator("課程表界面設(shè)置")

                constraintLayout {
                    backgroundColor = Color.WHITE

                    textView {
                        text = "自動隱藏周六日"
                        textSize = 14f
                        textColor = Color.BLACK
                    }.lparams(width = wrapContent, height = wrapContent) {
                        startToStart = PARENT_ID
                        topToTop = PARENT_ID
                        bottomToBottom = PARENT_ID
                        leftMargin = dip(16)
                    }

                    switch {
                        isChecked = SchedulePref.autoCollapseSchedule
                        onCheckedChange { _, isChecked ->
                            SchedulePref.autoCollapseSchedule = isChecked
                        }
                    }.lparams {
                        topToTop = PARENT_ID
                        bottomToBottom = PARENT_ID
                        endToEnd = PARENT_ID
                        rightMargin = dip(16)
                    }
                }.lparams(width = matchParent, height = dip(48))

                indicator("主題設(shè)置(課程表試點)")

            }
        }

        dialog.setContentView(view)
    }

你甚至可以像函數(shù)一樣去封裝,給LinearLayout做拓展后,就可以包裝添加固定風格TextView的操作了(這個封裝是不是就很好寫 就賊tm方便)

fun _LinearLayout.indicator(indicatorText: String) = frameLayout {
        textView {
            text = indicatorText
            textColor = getColorCompat(R.color.colorPrimary)
            textSize = 12f
            typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
        }.lparams(width = matchParent, height = wrapContent) {
            leftMargin = dip(8)
            topMargin = dip(8)
        }
    }.lparams(width = matchParent, height = wrapContent)

    fun lollipop(block: () -> Unit) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            block()
        }
    }

你甚至可以用for循環(huán)來做類似于適配器的事情(當然緩存是不會有緩存的 這輩子都沒有做的)

spreadChainLayout {
                    listOf(
                            "佩奇粉" to Color.parseColor("#EDC6CD"),
                            "喬治藍" to Color.parseColor("#6595D9"),
                            "豬媽黃" to Color.parseColor("#F4B17F"),
                            "豬爸綠" to Color.parseColor("#6FC6C5"),
                            "基佬紫" to Color.parseColor("#9C26B0")
                    ).forEachIndexed { index, (name, color) ->

                        verticalLayout {
                            colorCircleView {
                                this.color = color
                            }.lparams {
                                width = dip(24)
                                height = dip(24)
                                gravity = Gravity.CENTER_HORIZONTAL
                            }
                            textView {
                                text = name
                                textColor = color
                                textSize = 12f
                                typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
                            }.lparams(width = wrapContent, height = wrapContent) {
                                topMargin = dip(6)
                            }
                        }.lparams {
                            width = wrapContent
                            height = wrapContent
                            horizontalPadding = dip(16)
                        }.setOnClickListener {
                            val theme = CustomTheme.themeList[index]
                            Log.e(TAG, "custom theme: $theme")
                            val activity = this@CustomSettingBottomFragment.activity
                            Colorful().edit()
                                    .setPrimaryColor(theme)
                                    .setAccentColor(theme)
                                    .apply(context) {
                                        activity?.recreate()
                                    }
                        }


                    }
                }.lparams(width = matchParent, height = wrapContent) {
                    topMargin = dip(12)
                    bottomMargin = dip(12)
                }

在一個Layout的閉包里面寫循環(huán),填充數(shù)據(jù),然后addView,有了Kotlin的語法糖 + Anko變得很舒服。

你甚至可以在Recyclerview里面寫Anko


class Item(var text: String, var builder: (TextView.() -> Unit)? = null)

class ViewHolder(itemView: View?, val textView: TextView) : RecyclerView.ViewHolder(itemView)

override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder {
    lateinit var textView: TextView
    val view = parent.context.constraintLayout {
         textView = textView {
            text = "課程表設(shè)置"
            id = View.generateViewId()
            textSize = 16f
            textColor = Color.BLACK
        }.lparams(width = wrapContent, height = wrapContent) {
            startToStart = PARENT_ID
            topToTop = PARENT_ID
            bottomToBottom = PARENT_ID
            margin = dip(16)
        }
        imageView {
            backgroundColor = getColorCompat(R.color.common_lv4_divider)
        }.lparams(width = matchParent, height = dip(1)) {
            bottomToBottom = PARENT_ID
        }
    }.apply {
        layoutParams = RecyclerView.LayoutParams(matchParent, wrapContent)
    }
    return ViewHolder(view,textView)
}

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: Item) {
    item as SingleTextItem
    holder as ViewHolder
    holder.textView.text = item.text
    item.builder?.invoke(holder.textView)
}

在數(shù)據(jù)里面附著上一個閉包,便可以實現(xiàn)TextView的自定義(把邏輯從onBindViewHolder里面抽離出來),我們的項目中Recyclerview Adapter做了DSL風格的二次封裝,目前處于測試階段,穩(wěn)定了之后會分享在博客里面。

DSL大概是這樣子的:

        recyclerView.withItems {
            courseInfo(course = course)
            indicatorText("上課信息")

            val week = course.week
            course.arrangeBackup.forEach {
                iconLabel(CourseDetailViewModel(R.drawable.ic_schedule_location, "${week.start}-${week.end}周,${it.week}上課,每周${getChineseCharacter(it.day)}第${it.start}-${it.end}節(jié)\n${it.room}"))
            }

            indicatorText("其他信息")
            iconLabel(CourseDetailViewModel(R.drawable.ic_schedule_other, "邏輯班號:${course.classid}\n課程編號:${course.courseid}"))
            indicatorText("自定義(開發(fā)中 敬請期待)")
            iconLabel(CourseDetailViewModel(R.drawable.ic_schedule_search, "在蹭課功能中搜索相似課程"))
            iconLabel(CourseDetailViewModel(R.drawable.ic_schedule_event, "添加自定義課程/事件"))
            iconLabel(CourseDetailViewModel(R.drawable.ic_schedule_homework, "添加課程作業(yè)/考試"))
            indicatorText("幫助")
        }

做個總結(jié)?

DSL最吸引人的地方就在于,它可以在布局上加入邏輯,對于布局過程,它有著編程語言級別的控制,比如說封裝成類,封裝成函數(shù)什么的。這些東西在XML里面都是無法做到的,因為aapt工具的局限性,XML只能按照固定的格式寫布局 + 代碼控制來提供動態(tài)性,反正就很蛋疼。

而DSL可以解決很多問題,比如說用一個for循環(huán)來取代Adapter填充View功能,避免了很多無用的操作。比如說在布局里面加一個if就可以來操作一個控件的布局與否,而不是在findView之后控制Visibility,可以用Kotlin的閉包來封裝一個View的初始化操作什么的,重復(fù)的操作就可以封裝起來,再比如XML只能設(shè)置paddingLeft/paddingRight,在Anko DSL / 自定義DSL里面就可以很輕易的封裝出一個horizontalPadding。當然Anko因為避免了反射,提高了大量的性能。

DSL和XML并不是沖突的,DSL用于解決布局中細碎和動態(tài)的部分,而XML用于單頁布局,復(fù)雜布局。同時DSL和XML也可以無縫嵌合在一起,所以兩者并不是沖突的關(guān)系,也沒有必要去選擇“我到底該用DSL寫還是XML寫”,兩者各有優(yōu)點,了解Anko DSL并且與XML活用起來才是最優(yōu)解。XML可以拿到ViewGroup的應(yīng)用然后用DSL做騷操作,DSL也可以動態(tài)添加Inflate出來的XML來實現(xiàn)復(fù)雜頁面布局的添加

DSL和XML各有所長,DSL更適合用于頁面模塊的解耦,XML更多用于單頁構(gòu)建 / 復(fù)雜布局,兩者相互結(jié)合相互服務(wù)。

還想說的

Anko DSL讓人望而卻步的部分就是它不能支持即時預(yù)覽,所以這個局限性也就導(dǎo)致Anko無法構(gòu)建大型復(fù)雜的頁面。而當你的設(shè)計圖可以精確到dp的時候,完全可以用DSL來描述UI的各個小組件,因此DSL在這里不應(yīng)該被一棒子打死,DSL在目前的項目中,可以很好的替代手工new View, add view的部分,以及小規(guī)模的View控制。

如果你認真看了上面的內(nèi)容,并且有自己的體會,可以在已有的UI構(gòu)架中很快的用上Anko Layout來解決一些輕量級UI的構(gòu)建。比如說List中的一個Item,或者一個小Dialog之類。

沒有所謂的“最佳實踐”,對于業(yè)務(wù)與技術(shù)的一步步探索才是最重要的。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,027評論 25 709
  • Google在今年的IO大會上宣布,將Android開發(fā)的官方語言更換為Kotlin,作為跟著Google玩兒An...
    藍灰_q閱讀 77,194評論 31 489
  • 引言 前段時間寫了一篇Kotlin語法入門的文章,還沒有看過的盆友請戳(這里),有的可能看完之后已經(jīng)開始嘗試用ko...
    羅拙囈閱讀 6,365評論 9 31
  • 七色彩虹,點亮天空;七色彩虹,點亮天際;七色彩虹,美化上天;七色彩虹,美化人間。友誼之光,點綴星天;友誼之光,點...
    秋風清風南風北風閱讀 559評論 0 2
  • 一、2016年概述整體而言,2016年是我前幾輩子以來進步最快的一年。元認知能力相比往年得到巨大提升,這對我的行為...
    古嚴Pro閱讀 1,247評論 4 51

友情鏈接更多精彩內(nèi)容