从 Kotlin 中的子类按钮更新 UI
Updating the UI from subclassed buttons in Kotlin
我已经在 Kotlin 中子class编辑了一个按钮。 UI 中大约有 10 个按钮将继承这个新按钮 class、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 class 中,我在 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。
如何使用此子classed 按钮 class 更改按钮 1、3、5 上的 alpha?
在您的自定义按钮中添加此功能
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)
希望这对您有所帮助。
我已经在 Kotlin 中子class编辑了一个按钮。 UI 中大约有 10 个按钮将继承这个新按钮 class、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 class 中,我在 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。
如何使用此子classed 按钮 class 更改按钮 1、3、5 上的 alpha?
在您的自定义按钮中添加此功能
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)
希望这对您有所帮助。