是否可以将应用主题的资源 ID 获取到特定视图?

问题描述

给定一个View,是否可以获取当前应用主题的资源ID?我的意思不是针对整个活动(尽管如果没有应用特定视图,它将从该主题继承),我的意思是,如果我有

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

然后我希望能够获得 R.style.someTheme

的资源 ID

解决方法

不确定获取资源 ID 需要什么,但我能够获得此输出:

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

(将一种样式与以相同方式获得的另一种样式进行比较可能很有用)

从此:

//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());

我不知道如何获得诸如“R.style.ThemeNameImLookingFor”之类的返回值。

编辑: 找到了另一个选项,同样不是“R.style.ThemeIWant”,但可能有用(在这里找到并稍作修改: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;
}

返回(在上面相同的两个按钮上):

myapplication D/TEST: *************** 2131821007
myapplication D/TEST: *************** 2131821007