question

njsokalski avatar image
0 Votes"
njsokalski asked ·

TypedArray.GetColor - Specifying a Default Value

I am creating a compound control and using a TypedArray to retrieve the values from attrs.xml as follows:

 TypedArray ta = context.ObtainStyledAttributes(attrs, Resource.Styleable.CircleButton);

One of the values in attrs.xml is the following:

 <attr name="LabelTextColor" format="color"/>

When retrieving this value, the GetColor method asks for a second parameter as the default value, which I want to be a color from my color resources in colors.xml. However, because this parameter is an integer, I'm not quite sure what to use. My first thought was the following:

 ta.GetColor(Resource.Styleable.CircleButton_LabelTextColor, Resource.Color.White)

However, I'm not entirely sure if this is correct (I am still adjusting to Xamarin.Android's resource system). Will this do what I want, or do I need to specify the default value in some other way? Thanks.

dotnet-android
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

JessieZhang-2116 avatar image
0 Votes"
JessieZhang-2116 answered ·

Hello,


Welcome to our Microsoft Q&A platform!

If you want to specify a Default Value for method GetColor, you can try the following code:

   TypedArray ta = context.ObtainStyledAttributes(attrs, Resource.Styleable.test);

   var testColor = ta.GetColor(Resource.Styleable.test_testColor, Color.Red);
   SetTextColor(testColor);

If you want the color from your color resources in colors.xml, you can do like this:

             var myColor = ContextCompat.GetColor(context, Resource.Color.yellow);
             var testColor = ta.GetColor(Resource.Styleable.test_testColor, myColor);

And file attrs.xml is:

     <?xml version="1.0" encoding="utf-8" ?>
 <resources>
  <declare-styleable name="test">
  <attr name="text" format="string" />
  <attr name="testAttr" format="integer" />
  <attr name = "fontScale" format = "float" />
    
  <attr name="testColor" format="color|reference"/>
  </declare-styleable>
 </resources>

Best Regards,

Jessie Zhang


If the response is helpful, please click "Accept Answer" and upvote it.


Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.



· 1 ·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks! I think I was just confused by the fact that defValue was an int and Color.Red (or any Color) is of type Color, but your method seem to work. Thanks again!

0 Votes 0 ·