Tom Lenc
Tom Lenc

Reputation: 775

Redraw/refresh layout after changing Activity's theme/style

I have two themes defined in my styles.xml:

<style name="AppTheme" parent="android:Theme.Holo"></style>

<style name="AppLightTheme" parent="android:Theme.Holo.Light">
    <item name="android:background">#FFFFFF</item>
</style>

This is how I set the theme of an activity:

protected void changeTheme(boolean dark) {
    if (dark) {
        setTheme(R.style.AppTheme);
    } else {
        setTheme(R.style.AppLightTheme);
    }
}

Now after I change the theme, only the background stays the same UNTIL I open a different layout and go back. I'm using a DrawerLayout so I basically switch between layouts.

How can I re-draw it or kind of refresh it?

This is all I've tried that didn't do anything:

ViewGroup vg = findViewById (R.id.mainLayout);
vg.invalidate();

.

Intent intent = getIntent(); //this one is obvious, had to include so you don't try this unnecesarry.. code
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);

.

getWindow().getDecorView().findViewById(android.R.id.content).invalidate(); 

.

getWindow().getDecorView().findViewById(android.R.id.content).refreshDrawableState();

.

getWindow().getDecorView().findViewById(android.R.id.content).requestLayout();

.

findViewById(android.R.id.content).invalidate();

.

myLayout.invalidate();

Any ideas?

Upvotes: 0

Views: 3267

Answers (2)

Taufiqur Rahman
Taufiqur Rahman

Reputation: 41

recreate() is ok if your app is only targeting SDK level 11 and above. When need to restart an activity, you can use following code.

Bundle temp_bundle = new Bundle();
onSaveInstanceState(temp_bundle);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bundle", temp_bundle);
startActivity(intent);
finish();

and in onCreate...

@Override
public void onCreate(Bundle savedInstanceState) {

if (getIntent().hasExtra("bundle") && savedInstanceState==null){
    savedInstanceState = getIntent().getExtras().getBundle("bundle");
}

//add code for theme

switch(theme)
{
case LIGHT:
    setTheme(R.style.LightTheme);
    theme = LIGHT;
    break;
case BLACK:
    setTheme(R.style.BlackTheme);
    theme = BLACK;
    break;

default:
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code
}   

I've included code for switching theme. Here, 'theme' is a string variable.

Upvotes: 0

ianhanniballake
ianhanniballake

Reputation: 200130

You can call recreate() to recreate your activity and cause all Views to be recreated with the new theme.

protected void changeTheme(boolean dark) {
  if (dark) {
    setTheme(R.style.AppTheme);
  } else {
    setTheme(R.style.AppLightTheme);
  }
  recreate();
}

Upvotes: 5

Related Questions