Kotlin使用还是在参数中?

时间:2019-01-19 17:07:27

标签: android kotlin functional-programming overloading

我有两个函数和两个数组。函数和数组执行相同的操作,并且外观完全相同,不同的是一个输入一个字符串,另一个输入一个可扩展的字符串。

它们看起来像这样:

private fun createTextView(randomText: String): View {
        tv = TextView(context)
        val linearLevel1: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        tv.layoutParams = linearLevel1
        tv.gravity = Gravity.END
        tv.typeface = ResourcesCompat.getFont(context, R.font.blogger_sans_medium)
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25f)
        tv.text = randomText
        return tv
    }
    private fun createTextView(randomText: SpannableStringBuilder): View {
        tv = TextView(context)
        val linearLevel1: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        tv.layoutParams = linearLevel1
        tv.gravity = Gravity.END
        tv.typeface = ResourcesCompat.getFont(context, R.font.blogger_sans_medium)
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25f)
        tv.text = randomText
        return tv
    }

两个数组看起来像这样

private var textViewArr = ArrayList<String>()
private var textViewArrSpan = ArrayList<SpannableStringBuilder>()

无论如何我可以将它们结合起来吗?我是否可以使函数接受参数A或B或使用A或B初始化变量?我尝试在线搜索,发现一些地方建议我做已经做过的事情。想知道是否有更有效的方法。

2 个答案:

答案 0 :(得分:3)

StringSpannableStringBuilder都实现CharSequence,并且阅读TextView.setText()的文档时,它也需要CharSequence

所以我认为您可以这样做:

private fun createTextView(randomText: CharSequence): View {
    tv = TextView(context)
    val linearLevel1: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )
    tv.layoutParams = linearLevel1
    tv.gravity = Gravity.END
    tv.typeface = ResourcesCompat.getFont(context, R.font.blogger_sans_medium)
    tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25f)
    tv.text = randomText
    return tv
}

不是很重要,但很重要,我们也可以使它成为一个表达式...

private fun createTextView(randomText: CharSequence): View =
    TextView(context).apply {
        layoutParams = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        gravity = Gravity.END
        typeface = ResourcesCompat.getFont(context, R.font.blogger_sans_medium)
        setTextSize(TypedValue.COMPLEX_UNIT_SP, 25f)
        text = randomText
   }

答案 1 :(得分:0)

randomText的类型从StringSpannableStringBuilder更改为CharSequence