【问题标题】:how to pass property from control to drawable in android using xml? [duplicate]如何使用xml将属性从控件传递到android中的drawable? [复制]
【发布时间】:2020-10-20 04:33:56
【问题描述】:

我一直在寻找如何创建圆形按钮,它很简单。但我希望能够将颜色属性传递给可绘制对象,以便我可以为应用程序中的各种按钮传递不同的颜色,而不必为每种颜色创建单独的可绘制 xml。在 wpf 中,我们可以使用绑定来引用传入的属性,但我不确定在 android 中正确的方法是什么。

button_rounded.xml

     <Button   
         color = "white"
         android:background="@drawable/rounded_button"
                        />

     <Button   
          color = "blue"
          android:background="@drawable/rounded_button"
                        />

我希望能够将颜色从 xml 传递到可绘制圆形按钮,这样我就可以只维护一个 xml 文件。这在android中可能吗?

【问题讨论】:

  • 好吧,这不是我想要的。我真正想要的是一种在xml中设置形状的方法

标签: android


【解决方案1】:

在 Kotlin 中:

(yourButton.background as ShapeDrawable).paint.color = new_color_value

您还可以在分配给视图之前调整 ShapeDrawable。

val drawable = ContextCompat.getDrawable(context,R.drawable.your_shape) as ShapeDrawable
drawable.paint.color = your_another_color

另一种方法是使用backgroundTint

  <Button
      android: backgroundTint = "your_new_color"
      android: background = "@drawable/your_shape"
   />

【讨论】:

  • 我明白了。所以不能单独通过xml传递这些变量吗?
  • @JamesJoshuaStreet 我稍微修改了我的答案。
  • 谢谢你的菜鸟问题。我以前在 Windows 中做过这种事情,但直到昨天才不得不做 android gui。反正不确定我的 xml 代码有多好,但至少结果看起来很不错
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多