繁体   English   中英

android以编程方式更改style.xml中项目的值

[英]Change value of item in style.xml programmatically android

我是android开发的新手,目前正在制作计算器应用程序。 在其中,我的活动有多个按钮,我在这些按钮上应用了相同的样式。 代码的结构如下所示

layout.xml <LinearLayout> <Button android:text="Button 1" style="@style/styleName" > <Button android:text="Button 2" style="@style/styleName" > <Button android:text="Button 3" style="@style/styleName" > </LinearLayout> style.xml

<resources> <style name="styleName"> <item name="attribute1">attribute1Value</item> <item name="attribute2">attribute2Value</item> <item name="attribute3">attribute3Value</item> <item name="android:background">BackgroundValue</item> </style> </resources>

现在,我想向用户提供一项功能,当他/她从设置中选择特定主题时,所有按钮的背景都会改变。 如果可以在styleName中更改背景色的值,则可以实现此目的。 我不确定如何实现这一目标。 我在网上四处张望,却没有找到令人满意的答案。

显然,您无法以编程方式更改样式。如果我是您,则将在/res/drawable/创建许多selector.xml /res/drawable/如下所示:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:state_pressed="true"
    android:drawable="@drawable/light_btn_pressed" />
   <item
    android:state_pressed="false"
    android:drawable="@drawable/light_btn_normal" />
</selector>

对于每种“样式”,都有一个选择器(浅色,深色等)。 在可绘制中插入您的颜色或图像。 之后,您可以通过设置android:background="@drawable/my_button"来应用这些选择器。 另外,通过这种方法,您还将实现按钮状态之间的交互。

希望对您有所帮助

您可以通过Typed数组访问xml样式的属性。 假设您有一个customstyle xml。

 int[] attrs ={android.R.attr.textColor, android.R.attr.background,android.R.attr.text};
TypedArray array = obtainStyledAttributes(R.style.CustomStyle, attrs);

// Fetching the colors defined in your style
int textColor = array.getColor(0, Color.BLACK);
int backgroundColor = array.getColor(1, Color.BLACK);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM