【问题标题】:How to programmatically get value of built-in resources like colorAccent?如何以编程方式获取 colorAccent 等内置资源的价值?
【发布时间】:2017-08-31 11:21:30
【问题描述】:

如何获得参考颜色的实际值。在布局中,我可以使用以下...

android:textColor="?android:attr/colorAccent"

..这适用于将 TextView 的文本颜色设置为主题定义的强调色。如何在运行时使用代码获取 colorAccent 的值?

另外,你如何发现所有可用值的列表,我必须有一个很长的可用颜色列表,但该列表在哪里定义?

【问题讨论】:

    标签: android xamarin xamarin.android


    【解决方案1】:

    如果资源是 Android 定义的:

      var id = Android.Resource.Attribute.ColorAccent;
    

    如果资源在不是Android系统资源的Dialog、Widget等中(即获取DatePickerDialog资源)

      var id = SomeDatePickerDialog.Resources.GetIdentifier("date_picker_header_date", "id", "android");
    

    使用获得的id:

      var typedArray = Theme.ObtainStyledAttributes(new int[] { id });
      var color = typedArray.GetColor(0, int.MaxValue);
      if (color != int.MaxValue)
      {
          Log.Debug("COLOR", color.ToString());
      }
    

    R 列表随 API/主题而变化,用于可用的基本值:

    但要获得完整参考,您必须使用您正在查看的 API 的 Android 源代码:

    Oreo beta 中定义的颜色:

    然后在特定颜色的 xml 文件中查看它是如何定义的,并使用该定义来找到它的实际值(在 valueXXX 文件中的一个中......)

    【讨论】:

      【解决方案2】:

      对于您的示例,您可以通过以下方式获得该值:

      //default color instead the attribute is not set.
      var color = Color.Blue;
      
      var attributes = new int[] { Android.Resource.Attribute.ColorAccent };
      var typeArray = ObtainStyledAttributes(attributes);
      
      //get the fist item (we are sending only one) and passing
      //the default value we want, just in case.
      var colorAccent = typeArray.GetColor(0, color);
      

      colorAccent 将在您的主题中为ColorAccent 属性(如果有)或默认值设置Color。

      重要的是要提到此方法 ObtainStyledAttributes 是 Context 的一部分,因此如果您已经在 Activity 中,您会发现它是其中的一部分,但如果您在任何其他类中,则需要传入上下文,以防它不可用。

      有关可用值的完整列表,您可以从 Android.Resource.Attribute 类中获取。在 VS 中进行检查以查看此类具有的不同属性。不过,也许 Android 文档有更好的方法。

      希望这会有所帮助。-

      【讨论】:

        猜你喜欢
        • 2013-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-12-25
        • 2012-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多