简体   繁体   English

在Android中更改背景颜色

[英]Change background Colour in android

I am trying to let the user change the colour of my app via radio buttons. 我试图让用户通过单选按钮更改我的应用程序的颜色。 The user clicks on a radio button, and a method is called. 用户单击单选按钮,然后调用一个方法。 Now I want to change my 5 xml files background colour to x/y/z. 现在,我想将5个xml文件的背景色更改为x / y / z。 But I don't know how I am supposed to reference the xml files themselves, as they don't have an id.I have the 5 colours in string resources , so when i can reference the xml files, the background colour will be changed for all the files.(The hexadecimal notation of the colours replacing the strings). 但是我不知道应该如何引用xml文件本身,因为它们没有id。我在字符串资源中有5种颜色,因此当我可以引用xml文件时,背景颜色将被更改对于所有文件。(颜色的十六进制表示法替换字符串)。 Can it be done or do I have to go back on the merry go round again?? 可以做到吗,还是我必须重新回到快乐的地方?

 public void rbbgColourClicked(View view) {
            // Is the button now checked?
            boolean checked = ((RadioButton) view).isChecked();

            // Check which radio button was clicked
            switch(view.getId()) {
                case R.id.rbbgcolour_grey:
                    if (checked)
                        // Change to grey
                    break;
                case R.id.rbbgcolour_blue:
                    if (checked)
                        // Change to blue
                    break;


                case R.id.rbbgcolour_white:
                    if (checked)
                        // Change to white
                    break;



            }



  }

if I put in 如果我放

   LinearLayout one = (LinearLayout) findViewById(R.layout.preferences);
                        one.setBackgroundColor(0xff888888);

can't understand why its there. 不明白为什么它在那里。

Thanks 谢谢

Use setBackgroundResource() 使用setBackgroundResource()

Example: 例:

view.setBackgroundResource(R.id.rbbgcolour_grey);
LinearLayout ll = (LinearLayout) findViewById(R.id.myLinearLayout);
ll.setBackgroundColor(getResources().getColor(R.color.red));

You can do this using SharedPreferences. 您可以使用SharedPreferences执行此操作。 You can store the background color hexadecimal code as a preference. 您可以将背景色十六进制代码存储为首选项。 When user clicks a radio button, you have to change the hexadecimal code in SharedPreferences. 用户单击单选按钮时,必须在SharedPreferences中更改十六进制代码。 It is something like this.... 是这样的...

in onCreate of each activity... 在每个活动的onCreate中...

SharedPreferences sp = getSharedPreferences("MyPref", 0);
String hexaColor = sp.getString("hexa", "#000000"); //default color will be #000000

Then set this as background color of those activities. 然后将此设置为那些活动的背景色。

When user clicks a radio button then do this... 当用户单击单选按钮时,请执行此操作...

SharedPreferences sp = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sp.edit();
editor.putString("hexa", "new hexa code");
editor.commit();

hope this will help you. 希望这会帮助你。

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

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