如何以编程方式更改TextView颜色

tal*_*aul 6 c# android visual-studio xamarin

我对这个看似简单的任务感到难过.

我想简单地将a的颜色和a textview的背景颜色更改为linearlayout我的colors.xml资源文件中设置的颜色.

我试过了:

myTextView.SetTextColor(this.Resources.GetColor(Resource.Color.myColor));
Run Code Online (Sandbox Code Playgroud)

但这已被弃用.

然后我尝试了:

myTextView.SetTextColor(ContextCompat.GetColor(context, Resource.Color.myColor));
Run Code Online (Sandbox Code Playgroud)

但是ContextCompat.GetColor()返回一个int而不是一个Android.Graphics.Color不会编译.

然后我尝试将颜色设置为style:

  <style name="myColorStyle">
    <item name="android:textColor">
      @color/myColor
    </item>
...
  </style>
Run Code Online (Sandbox Code Playgroud)

并首先使用它

myTextView.SetTextAppearance(this, Resource.Style.myColorStyle);
Run Code Online (Sandbox Code Playgroud)

但这也被弃用了

我试过这个:

myTextView.SetTextAppearance(Resource.Style.myColorStyle);
Run Code Online (Sandbox Code Playgroud)

但这引发了一个例外:

Java.Lang.NoSuchMethodError:没有非静态方法"Landroid/widget/TextView; .setTextAppearance(I)V"

这个简单的任务是如何实现的?

使用Xamarin和Visual Studio 在C#中编码.

Mic*_*bay 10

在2017年,这是通过资源ID获取颜色的正确方法,即使它看起来非常复杂:

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

per:https: //forums.xamarin.com/discussion/54193/res-getcolor-is-deprecated


Shr*_*hna 7

不需要那么复杂,只需使用

myTextView.setTextColor(Color.parseColor("#000"));
Run Code Online (Sandbox Code Playgroud)

或者

 myTextView.setTextColor(Color.parseColor("red"));
Run Code Online (Sandbox Code Playgroud)

或者

myTextView.setTextColor(getResources().getColor(R.color.YOURCOLOR));
Run Code Online (Sandbox Code Playgroud)


Maj*_*jkl 2

更新

我首先没有注意到它,但我看到你已经尝试过这个解决方案。您使用什么版本?在我看来,它并没有被弃用。

 textView.SetTextColor(Resources.GetColor(Resource.Color.red));
Run Code Online (Sandbox Code Playgroud)

在资源/值/colors.xml中

<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <color name="red">#ff0000</color>
  <color name="blue">#0000ff</color>
</resources>
Run Code Online (Sandbox Code Playgroud)

Xamarin 资源.颜色