4

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?

  • `i should use super (of activity).setTheme instead of activity.setTheme` this is wrong. `But it crashes` with crash details in the logcat – Vladyslav Matviienko Jun 06 '19 at 04:46
  • this question is not duplicate of given above [link](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this). – Yagnesh Lashkari Jan 18 '22 at 06:17

2 Answers2

5

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);
}
Ridcully
  • 23,362
  • 7
  • 71
  • 86
Yagnesh Lashkari
  • 228
  • 4
  • 15
0

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); }