【问题标题】:Is it possible to get the resource ID of the applied theme to a specific View?是否可以将应用主题的资源ID获取到特定视图?
【发布时间】:2021-02-24 19:49:21
【问题描述】:

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

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

那么我希望能够得到R.style.SomeTheme的资源ID

【问题讨论】:

    标签: android android-layout android-resources android-identifiers


    【解决方案1】:

    不确定您需要获取资源 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
    

    【讨论】:

    • 谢谢,这部分可行,但返回的是视图所在的Context 的主题,而不是视图本身。例如,如果button.contextContextThemeWrapper,这将返回应用于that 的主题,而不是Button 本身。否则,它将回退到清单中 &lt;application&gt; 标记中定义的主题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多