2017-01-22 38 views
-1

我需要在运行时更改应用程序的颜色。我分析的数据文件,以获得颜色和我与静态字段和方法保存在类:以编程方式更改可绘制xml文件中的颜色

public class Colors { 

    private static String colorOneBackground = "#00577F"; 
    private static String colorOneForeground = "#FFFFFF"; 

    public static void setColorOneBackground(String colorOneBackground) { 
     Colors.colorOneBackground = colorOneBackground; 
    } 

    public static int getColorOneForeground() { 
     return Color.parseColor(colorOneForeground); 
    } 
    // more colors... 

然后,例如,当我想改变屏幕的背景我愿意这样做:

RelativeLayout relativeLayout = (RelativeLayout) myView.findViewById(R.id.loginBackground); 
     relativeLayout.setBackgroundColor(Colors.getColorOneBackground()); 

与文字浏览和其他小工具一样。但是,我遇到了一个问题。有些款式在可绘制文件夹中定义,例如, mybutton.xml:

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android=" http://schemas.android.com/apk/res/android " 
    android:shape="rectangle"> 
    <gradient 
     android:startColor="#FFFFFF" 
     android:centerColor="#FFFFFF" 
     android:endColor="#FFFFFF" 
     android:angle="270" /> 
    <corners android:radius="5dp" /> 
    <stroke android:width="3px" android:color="#000000" /> 
</shape> 

而且我设置为我的按钮的背景:

<Button 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/title" 
    android:background="@drawable/mybutton" /> 

正如我说我要以编程方式更改这些颜色值。所以我想知道是否有可能在xml文件中定义颜色值?

+0

使用** setBackGroundRes()方法**。 –

+0

请再次阅读我的问题。我想改变xml文件中的颜色值,我知道如何在代码中设置可绘制背景 –

+0

http://stackoverflow.com/questions/17823451/set-android-shape-color-programmatically – amorenew

回答

2

试试这个:而改变颜色的绘制xml文件:

button.setBackgroundResource(R.drawable.mybutton); //drawable id 
GradientDrawable gd = (GradientDrawable) button.getBackground().getCurrent(); 
gd.setColor(Color.parseColor("#000000")); //set color 
gd.setStroke(2, Color.parseColor("#00FFFF"), 5, 6); 
+0

我终于设法自己解决问题了...无论如何,感谢您的帮助;) –

+0

比发表您的答案 – Merian

相关问题