Android App : Apply Color Theme Dynamically at Runtime

 ̄綄美尐妖づ 提交于 2019-12-13 16:36:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!