0

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

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

然后我希望能够获取资源 IDR.style.SomeTheme

4

1 回答 1

0

不知道你需要什么来获取资源 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
于 2021-02-26T00:40:35.277 回答