How can I allow the user to set the background color?

时间:2015-05-24 20:23:09

标签: java android

I have created a simple app that shows the user random quotes. I would like to allow the user to change the background color of the app.

How would I go about doing this? I have created a menu, with a settings activity. What would I need to do to allow them to set the color?

I read about using SharedPreferences, but can't find anywhere that explains it to my level of understanding.

Would it be possible to do something like this:

android:background="selectedColor">

Then get user input and set:

selectedColor = "@color/" + "userInput"

Please ELI5, this is the first time I've tried building an app, so I'm going to try and slowly add different 'features'. It's more of a learning thing, than to actually create a useful app too!

2 个答案:

答案 0 :(得分:1)

You need to get the View in which you would like change the color by View v = findViewById(R.id.yourViewId) in the Activity, and then call on this View v.setBackgroundColor(int color);

You can cast the View to proper type to get possibility of using other methods.

答案 1 :(得分:0)

Store in SharedPreferences a value of the hex color you want. And always use the value associated a certain key as the background, since preferences can have a "default value" when reading them

Somethis along these lines:

//Reading
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.getString("colorbg","#FFFFFF");//#FFFFFF would be the default one

.

//Writing
prefs.edit().putString("colorbg","#FF0000").commit(); //Next read would be #FF0000