Set theme color dynamically

后端 未结 5 1433
北荒
北荒 2020-12-14 23:31

I am using themes (dynamically) in my android app, like this:

my_layout.xml (extract):



        
5条回答
  •  不思量自难忘°
    2020-12-14 23:58

    Given the fact that every resource is a field into the R class, you can look for them using reflection. That's costly, but since you are going to get an int value, you can store them after you get them and avoid the performance drop. And since the methods that use resources take any int, you can use an int variable as placeholder, and then put the desired color into it.

    for getting any resource:

    String awesomeColor = "blue";
    int color = getResourceId(R.color, awesomeColor, false);
    if(blue>0) ((TextView) findViewById(R.id.myItem)).setTextColor(color);
    

    The function:

    public static int getResourceId(Class rClass, String resourceText, boolean showExceptions){
    
            String key = rClass.getName()+"-"+resourceText;
    
            if(FailedResourceMap.containsKey(key)) return 0;
            if(ResourceMap.containsKey(key)) return ResourceMap.get(rClass.getName()+"-"+resourceText);
    
            try {
    
                String originalText = resourceText;
                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.GINGERBREAD){
                    resourceText = ValidationFunctions.normalizeText(resourceText);
                }
                resourceText = resourceText.replace("?", "").replace("  ", " ").replace(" ", "_").replace("(", "").replace(")", "");
    
                int resource = rClass.getDeclaredField(resourceText).getInt(null);
                ResourceMap.put(rClass.getName()+"-"+originalText, resource);
    
                return resource;
            } catch (IllegalAccessException | NullPointerException e) {
                FailedResourceMap.put(key, 0);
                if(showExceptions) e.printStackTrace();
            } catch (NoSuchFieldException e) {
                FailedResourceMap.put(key, 0);
                if(showExceptions) e.printStackTrace();
            }
    
            return 0;
        }
    

    Working version here: https://github.com/fcopardo/AndroidFunctions/blob/master/src/main/java/com/grizzly/functions/TextFunctions.java

    This treatment is valid for any android resource. You can set the theme this way too instead of using intermediate variables:

    public static void onActivityCreateSetTheme(Activity activity)
      {
        int theme = getResourceId(R.style, activity.getClass().getSimpleName(), false);
        if(theme > 0) activity.setTheme(theme);
      }
    

提交回复
热议问题