问题
In My Application I want to support such functionality where users can select color from the list (which is downloaded from WebService) and as User selects any color(say Orange) all the Buttons in my application will have background color as Orange.
I have checked solutions like http://www.androidengineer.com/2010/06/using-themes-in-android-applications.html but with that I need to have different styles created with different color in my app.
My need is I only support one style only background colors need to be changed according selection and for that I don't want to fetch all my buttons at runtime and apply that color.
So please suggest any other better solutions to apply selected color to all the buttons in the application without fetching all buttons in activities and setting their background color.
回答1:
You could fill a Bitmap
with a particular color.
private BitmapDrawable makeColorFillDrawable(int color, Drawable d) {
Bitmap maskBitmap = ((BitmapDrawable) d).getBitmap();
final int width = maskBitmap.getWidth();
final int height = maskBitmap.getHeight();
maskBitmap = null;
final Bitmap outBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(outBitmap);
d.setBounds(0, 0, width, height);
d.setColorFilter(color, PorterDuff.Mode.SRC_IN);
d.draw(canvas);
d.setColorFilter(null);
d.setCallback(null);
return new BitmapDrawable(getResources(), outBitmap);
}
Save the color you fetch from your server in your SharedPreferences
. Then subclass Button
and apply the color fill drawable based on the value you saved. All you'd need to do then is replace <Button.../>
in your XML with the path to your custom one.
Here's an example with the ActionBar
icon.
final Drawable d = getResources().getDrawable(android.R.drawable.sym_def_app_icon);
getActionBar().setIcon(makeColorFillDrawable(Color.RED, d));

来源:https://stackoverflow.com/questions/22529646/android-app-apply-color-theme-dynamically-at-runtime