Programmatically Access Properties of Drawable Defined in XML

Nathan Sokalski 4,111 Reputation points
2022-12-12T03:18:35.49+00:00

I have a Drawable which is used as the Background for a View. I want to dynamically modify the width & color of the stroke attribute. The xml is as follows:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">  
	<solid android:color="@color/Transparent"/>  
	<stroke android:width="3dp" android:color="@color/White"/>  
	<corners android:radius="27dp"/>  
</shape>  

I am able to obtain the Drawable as a GradientDrawable using the following:

GradientDrawable cbb = (GradientDrawable)this.btnCircleButton.Background;  

I am able to set the properties with no trouble using the SetStroke, SetColor & SetCornerRadius methods, but I cannot figure out how to obtain the current values. How can I programmatically determine the current values of the properties of the solid, stroke & corners tags?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,380 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2022-12-13T03:14:58.627+00:00

    Hello,

    In the native Android platform, by referring to Drawable resources, you could see that the corresponding object for Shape.xaml is GradientDrawable.

    An XML file that defines a geometric shape, including colors and gradients. Creates a GradientDrawable.

    As for GradientDrawable, by referring to this native API documentation GradientDrawable, you could see which properties can be fetched.

    On Xamarin, you could use the following code to get the values of corners:

       var d = button.Background as GradientDrawable;  
       d.CornerRadius;  
    

    However, it is impossible to get the value of solid and stroke, due to Android natively does not provide relevant API support.

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    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.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.