Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the theme of a singleTop activity

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):

  • Why getApplicationContext().setTheme() in a Activity does not work?
  • http://code.google.com/p/android/issues/detail?id=4394

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?

like image 434
Eric Avatar asked Nov 05 '22 03:11

Eric


2 Answers

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.

like image 168
Udinic Avatar answered Nov 13 '22 04:11

Udinic


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."

like image 32
adamp Avatar answered Nov 13 '22 04:11

adamp