How to use superclass in static method with given Activity parameter?

Viewed 88

I `m trying to create static class ActivitySetup that is used to set language, theme, etc. for my activities. I have a problem with setting theme. Now i have following code:

     static void configureTheme(Activity activity, int defaultTheme) {
     String theme = PreferenceManager.getDefaultSharedPreferences(activity).getString("theme", "light");
     assert theme != null;

     switch (theme) {
         case "light":
             activity.setTheme(R.style.AppTheme);
             break;
         case "dark":
             activity.setTheme(R.style.Theme_AppCompat);
             break;
         default:
             activity.setTheme(defaultTheme);
             break;
     }
 }

But it crashes. I know that i should use super (of activity).setTheme instead of activity.setTheme, but how can i do that? How to pass instance of superclass as parameter to a static method?

2 Answers

switch between themes dynamically you simply need to call setTheme before super.onCreate

public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.Theme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

Thanks. That is the answer i found:

    static int getThemeRes(Activity activity) throws Resources.NotFoundException {
    String theme = PreferenceManager.getDefaultSharedPreferences(activity).getString("theme", "light");
    assert theme != null;

    switch (theme) {
        case "light":
            return R.style.AppTheme;
        case "dark":
            return R.style.Theme_AppCompat;
        default:
            throw new Resources.NotFoundException();
    }
}

Call to this method in all activities:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(ActivitySetup.getThemeRes(this));
    super.onCreate(savedInstanceState);
    setContentView(LAYOUT); }
Related