0

Given a View, is it possible to get the resource ID of the currently-applied theme? I don't mean to the whole activity (though it would inherit from that theme if there's no specific view applied to it), I mean, if I have:

<Button
    ...
    style="@style/SomeTheme" />

Then I want to be able to get the resource ID for R.style.SomeTheme

Dr Mido
  • 2,414
  • 4
  • 32
  • 72
Tyler
  • 1

1 Answers1

1

Not sure what you need to get the resource ID for, but I was able to get this output:

myapplication D/TEST: **************
Theme is android.content.res.Resources$Theme@d97185b
myapplication D/TEST: **************
Theme is android.content.res.Resources$Theme@d97185b

(might be useful to check one style against another gotten in the same manner)

From this :

//two buttons with the same theme
   Button buttontoCheck = view.findViewById(R.id.button_first);
   Button buttontoCheck2 = view.findViewById(R.id.btnBitmap);
   
   Context themeToCheck = buttontoCheck.getContext();
   Context themeToCheck2 = buttontoCheck2.getContext();
  
   Resources res = themeToCheck.getResources();
   Resources res2 = themeToCheck2.getResources();
  
   Resources.Theme result = themeToCheck.getTheme();
   Resources.Theme result2 = themeToCheck2.getTheme();

   Log.d("TEST", "**************\n" + "Theme is " + result.toString());
   Log.d("TEST", "**************\n" + "Theme is " + result2.toString());

I do not know how to get the return of something like "R.style.ThemeNameImLookingFor".

EDIT: Found one more option, again not the "R.style.ThemeIWant" but might be useful (found here and slightly modified: https://stackoverflow.com/a/26302184/14111809)

  public int getThemeId(View v) {
    try {
        Class<?> wrapper = Context.class;
        Method method = wrapper.getMethod("getThemeResId");
        method.setAccessible(true);
        return (Integer) method.invoke(v.getContext());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}

Which returns (on same two buttons above):

myapplication D/TEST: *************** 2131821007
myapplication D/TEST: *************** 2131821007
Matt Grier
  • 206
  • 2
  • 9
  • Thank you, and this partially works, but that returns theme of the `Context` the view is in, not the view itself. For example, if the `button.context` is a `ContextThemeWrapper`, this will return the theme applied to *that*, not the `Button` itself. Otherwise, it will fallback to what the theme defined in the `` tag in the manifest is. – Tyler Feb 26 '21 at 14:56