【问题标题】:Anko equivalent to style attr in xmlAnko 相当于 xml 中的样式 attr
【发布时间】:2017-01-24 15:41:04
【问题描述】:

我需要创建无边框按钮。在 xml 中设置Widget.AppCompat.Button.Borderless 的最简单方法。我正在尝试使用Anko

button(theme = R.style.Widget_AppCompat_Button_Borderless_Colored, text = "Send") {
    horizontalGravity = Gravity.END
    lparams(wrapContent, wrapContent)
}

但是没有效果。我做错了什么?

【问题讨论】:

    标签: android kotlin anko


    【解决方案1】:

    尝试使用第三个构造函数参数,它接受attr资源:

    addView(Button(activity, null, R.attr.borderlessButtonStyle))
    

    另外,您可以将其声明为 DSL 组件:

    fun ViewManager.borderlessButton(textRes: Int = 0) =
            borderlessButton(textRes) { }
    
    fun ViewManager.borderlessButton(textRes: Int = 0, init: Button.()->Unit) =
            ankoView({ Button(it, null, R.attr.borderlessButtonStyle) }, 0) {
                if (textRes != 0) setText(textRes)
                init()
            }
    

    然后,您的呼叫站点可能如下所示:

    borderlessButton(android.R.string.ok)
    

    你可以看看 Anko 的 horizontalProgressBar 方法和 HORIZONTAL_PROGRESS_BAR_FACRTORY 声明方式类似。

    【讨论】:

      【解决方案2】:

      顺序错误。试试这个:

      button("Your text", android.support.design.R.style.Base_Widget_AppCompat_Button_Borderless_Colored) {
        //your params
       }
      

      这对我有用。

      【讨论】:

      • Kotlin 有命名参数,如果你命名它们就不需要保持顺序(如问题所示)
      猜你喜欢
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      • 2016-07-14
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多