Xamarin Android:以编程方式从colors.xml获取颜色值

Mar*_*nek 5 c# xml android xamarin

如何从colors.xml文件以编程方式获取颜色值到C#代码?

这是我的colors.xml:

<?xml version="1.0" encoding="utf-8" ?>
<resources>

  <item name="row_a" type="color">#FFCCFFCC</item>
  <item name="row_b" type="color">#FFFFFFCC</item>
  <item name="all_text" type="color">#FF000000</item>
  <item name="row_red" type="color">#FFFF4444</item>
  <item name="row_orange" type="color">#FFE69900</item>
  <item name="row_green" type="color">#FF739900</item>
  <item name="wheat" type="color">#FFF5DEB3</item>

  <integer-array name="androidcolors">
    <item>@color/row_a</item>
    <item>@color/row_b</item>
    <item>@color/all_text</item>
    <item>@color/row_red</item>
    <item>@color/row_orange</item>
    <item>@color/row_green</item>
    <item>@color/wheat</item>
  </integer-array>

</resources>
Run Code Online (Sandbox Code Playgroud)

我试过了:

Color t = (Color)Resource.Colors.wheat;
Run Code Online (Sandbox Code Playgroud)

但当然我不能用这种方式将int值转换为Color.

编辑:

正如我所建议的那样

Color t = Resources.GetColor(Resource.Color.row_a);
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误:

Error   CS0120  An object reference is required for the non-static field, 
method, or property 'Resources.GetColor(int)'
Run Code Online (Sandbox Code Playgroud)

Mar*_*nek 5

问题是我试图从ListView Adapter访问资源.解决方案是使用:

parent.Resources.GetColor(Resource.Color.row_a)
Run Code Online (Sandbox Code Playgroud)

其中parent通入public override View GetView(int position, View convertView, ViewGroup parent)方法.

  • 这个方法现在已经弃用了,现在你可以这样做`new Android.Graphics.Color(ContextCompat.GetColor(this, Resource.Color.color_name))` (3认同)
  • @CodeIt 出于好奇,您知道*为什么*不推荐使用`Resources.GetColor` 方法吗?这种新的“ContextCompat”做事方式似乎非常冗长 (2认同)

Fet*_*mos 5

试试这个代码:

  Color t = new Android.Graphics.Color (ContextCompat.GetColor (this, Resource.Color.row_a)); 
Run Code Online (Sandbox Code Playgroud)