8

I want to know which theme is applied for an Activity in an application.

Normally we are setting the theme by using

setTheme(android.R.style.Theme_Light);

Here we are specifying style, As like this can we able to get the specific style type exactly applied for an activity programmatically.

Thanks

Sruthi Mamidala
  • 361
  • 1
  • 3
  • 10

1 Answers1

17

Context class has a nice method called getThemeResId, however it's private thus you need to use reflection.

Here's an example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    Log.e("TAG", "Def theme: " + R.style.AppTheme);
    Log.e("TAG", "Light theme: " + android.R.style.Theme_Light);
    Log.e("TAG", "Current theme id: " + getThemeId());

    setTheme(android.R.style.Theme_Light);
    Log.e("TAG", "Current theme id: " + getThemeId());
}

int getThemeId() {
    try {
        Class<?> wrapper = Context.class;
        Method method = wrapper.getMethod("getThemeResId");
        method.setAccessible(true);
        return (Integer) method.invoke(this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}
Simas
  • 43,548
  • 10
  • 88
  • 116
  • 1
    It seems it's not working now.. at least in kotlin. – mazend Aug 18 '22 at 11:27
  • This uses reflection to access a private API. This solution is not reliable as the private API can change anytime, therefore it could break your app. – dephinera Mar 02 '23 at 08:52