Reputation: 5402
So I've got an activity in my app that is currently marked as
android:launchMode="singleTop"
...and I currently have logic in both onCreate and onNewIntent to make sure that the screen is always showing the data delivered by the newest Intent that launched. And I'd like to be able to change between Holo.Light and Holo.Dark based on the data delivered by that Intent.
Calling setTheme doesn't work (see these two links):
That second link has a workaround that involves creating a second AndroidManifest.xml entry that has the other theme and points to an empty subclass of the activity in question. This works, but it breaks singleTop (since there can now be two instances of the activity on the stack).
I'm out of ideas. Anybody know if there's any way to do this aside from rolling my own custom ActionBar view for this activity?
Upvotes: 5
Views: 1434
Reputation: 10542
I'll post my solution that doesn't really add nothing new here but merge the various tips together.
After changing the Theme of the activity and optionally ( depends on what you are looking for ) of the application:
public void updateTheme( Activity a, int themeID ) {
a.getApplication().setTheme( themeID );
a.setTheme( themeID );
}
You then have to recreate the activity ( just as after a configuration change ). For the OS 11> there is a API , instead for previous versions you have to force it finishing and restarting the activity just as Udinic pointed out.
public boolean isBeforeHoneycomb() {
return Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB;
}
public void reload() {
if( isBeforeHoneycomb() ) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}else{
recreate();
}
}
Upvotes: 0
Reputation: 3064
You need to set the theme using the setTheme() method, but then to reload the activity.
I have a singleTask activity, and a code that runs on API<11, so I have this code to reload the activity:
public void reload() {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
I'm pretty much just finishing the activity and calling it again. I disable any transition animation to make the reloading look instant.
Upvotes: 1
Reputation: 28932
Since you're referring to the Holo themes I assume you're working with API 11+.
API 11 added the method Activity#recreate()
, which sends your current activity through the same teardown/recreate process that normally happens for config changes such as rotating the screen between landscape and portrait orientation. Your onCreate method will be called again on a new Activity instance, allowing you to set the theme on the Activity before the window is initialized as usual.
The Google Books apps uses this tactic to switch between light/dark themes for "night mode."
Upvotes: 1