Masoud Nazari
Masoud Nazari

Reputation: 496

Android: change application theme in java

I'm trying to build a multiTheme application. I want set theme of whole of application in java code. It can be set in XML in this way in Manifest file:

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/myTheme" >

I store the selected theme ID in SharedPreferences. I have tried the following code in my launcher activity:

getApplicationContext().setTheme(R.style.mainTheme2); 
setContentView(R.layout.activity_action_selection);

///////////////////////////////////////////////////////////////////

getApplication().setTheme(R.style.mainTheme2);
setContentView(R.layout.activity_action_selection)  ;

////////////////////////////////////////////////////////////////////

setTheme(R.style.mainTheme2);
setContentView(R.layout.activity_action_selection)  ;

The last code change the activity theme, but not the application theme! others does not change anything!

How can i change the application theme in java codes?!

Upvotes: 1

Views: 1239

Answers (1)

Eugen Pechanec
Eugen Pechanec

Reputation: 38243

When the theme changed you stored it probably somewhat similar to this:

SharedPreferences prefs = getSharedPreferences("theme", Context.MODE_PRIVATE);
prefs.edit().putInt("resId", R.style.Theme_AppCompat).commit();

When you stored the currently selected theme ID in SharedPreferences the only thing you have to do is read the value in onCreate of any Activity that you want to respect this theme like so:

public class ThemedActivity extends ActionBarActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // read current custom theme from preferences
    SharedPreferences prefs = getSharedPreferences("theme", Context.MODE_PRIVATE);
    int resId = prefs.getInt("resId", R.style.Theme_AppCompat_Light);
    setTheme(resId);

    // business as usual
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
  }
}

If you want to apply the theme immediately to current activity restart it after you make changes to the SharedPreferences:

startActivity(getIntent()); // this comes first to ensure valid context
finish();

Upvotes: 2

Related Questions