简体   繁体   English

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

[英]Xamarin Android: getting color value from colors.xml programmatically

How can I get value of color programmatically from colors.xml file into C# code?如何以编程方式将颜色值从 colors.xml 文件转换为 C# 代码?

Here is my colors.xml:这是我的 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>

I tried:我试过了:

Color t = (Color)Resource.Colors.wheat;

but of course I cannot convert int value to Color this way.但当然我不能以这种方式将 int 值转换为 Color 。

EDIT:编辑:

As suggested I tried按照建议我试过了

Color t = Resources.GetColor(Resource.Color.row_a);

But it gives me an error:但它给了我一个错误:

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

Problem was that I tried to access Resources from ListView Adapter. 问题是我试图从ListView Adapter访问资源。 Solution is to use: 解决方案是使用:

parent.Resources.GetColor(Resource.Color.row_a)

where parent is passed into public override View GetView(int position, View convertView, ViewGroup parent) method. 其中parent传递给public override View GetView(int position, View convertView, ViewGroup parent)方法。

试试这段代码:

  Color t = new Android.Graphics.Color (ContextCompat.GetColor (this, Resource.Color.row_a)); 
public class MainActivity : AppCompatActivity
{
    protected override void OnCreate(Bundle savedInstancesState)
    {
        // check your Resources/Resource.designer.cs file
        int nResId = Resource.Color.row_a;
        var colorValue = ApplicationContext.GetColor(nResId);
    }
}

Android.Content.Context.GetColor Android.Content.Context.GetColor

Android Resources Android 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM