【问题标题】:Updating the UI from subclassed buttons in Kotlin从 Kotlin 中的子类按钮更新 UI
【发布时间】:2019-11-25 23:58:48
【问题描述】:

我在 Kotlin 中对 Button 进行了子类化。 UI 中大约有 10 个按钮将继承这个新的按钮类 CustomButton

为了一个非常简单的概念证明,我尝试将一些按钮的 halfAlpha 属性设置为 true,以将 alpha 更改为 0.5f

class CustomButton : Button {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs){
        if (halfAlpha){
            this.alpha = 0.5f
        }
    }
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs,
        defStyleAttr)

    var halfAlpha = false
}

在我的 MainActivity 类中,我在 onCreate 中调用了这个函数:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    lockButtons()
}

private fun lockButtons(){
    button1.halfAlpha = true
    button2.halfAlpha = false
    button3.halfAlpha = true
    button4.halfAlpha = false
    button5.halfAlpha = true
    // etc...
}

问题是...按钮 1、按钮 3 和按钮 5 的 alpha 值永远不会更改为 0.5。

如果我在 CustomButton 中设置var halfAlpha = true,那么所有按钮的 alpha 都是 0.5。

如何使用这个子类 Button 类更改按钮 1、3、5 的 alpha?

【问题讨论】:

  • 您只是在其构造函数中设置了Buttonalpha,并且直到在布局期间构造了Buttons 之后才设置那些halfAlphasetContentView() 中的通货膨胀。

标签: android button kotlin subclass android-button


【解决方案1】:

在您的自定义按钮中添加此功能

fun setAlpha(isHalfAlpha: Boolean) {

    if (halfAlpha){
        this.alpha = 0.5f
    }
}

调用它

button1.setAlpha(true)
button2.setAlpha(false)
button3.setAlpha(true)
button4.setAlpha(false)
button5.setAlpha(true)

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    相关资源
    最近更新 更多