我正在使用Android Toggle library作者:Angad Singh,以编程方式创建 LabeledSwitch,一切正常,但我无法为边框着色。
LabeledSwitch switch = new LabeledSwitch(context);
switch.setLayoutParams(lp);
switch.setColorDisabled(context.getResources().getColor(R.color.colorDisabled));
switch.setColorOn(context.getResources().getColor(R.color.colorPrimary));
switch.setLabelOn("Yep!");
switch.setLabelOff("Nope!");
xml 属性是 app:colorBorder
,如果我编写此属性,我会收到以下消息:
'colorBorder' has private access in 'com.github.angads25.toogle.LabeledSwitch'
如何以编程方式更改 LabeledSwitch 边框颜色? (不是 XML)
最佳答案
val view = v.findViewById<LinearLayout>(R.id.container)
val lp = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
val switch1 = LabeledSwitch(activity)
switch1.layoutParams = lp
switch1.colorDisabled = ContextCompat.getColor(activity!!, R.color.colorAccent)
switch1.colorOn = ContextCompat.getColor(activity!!, R.color.colorPrimary)
switch1.labelOn = "Yep!"
switch1.labelOff = "Nope!"
switch1.colorBorder = ContextCompat.getColor(activity!!, android.R.color.black)
view.addView(switch1)
首先,您需要使用 ContextCompat 来获取颜色资源,而不是使用 resources.getColor()
对于我来说,它似乎对更新的版本 1.1.0 再次有效,也许您需要更新您的依赖项。
编辑
如果您使用 kotlin,则需要使用赋值字符 =
而不是使用括号。
如果您使用 java,则需要使用 setColorBorder
代替。
关于java - 如何以编程方式更改 Android Toggle/LabeledSwitch 边框颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60495052/