summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.Android/ResourcesProvider.cs
blob: 5c7e1de3efb7018ec3aa823adfa2d06f38ba0882 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using Android.Content;
using Android.Content.Res;
using Android.Util;

namespace Xamarin.Forms.Platform.Android
{
	internal class ResourcesProvider : ISystemResourcesProvider
	{
		ResourceDictionary _dictionary;

		public IResourceDictionary GetSystemResources()
		{
			_dictionary = new ResourceDictionary();

			UpdateStyles();

			return _dictionary;
		}

		public Style GetStyle(int style)
		{
			var result = new Style(typeof(Label));

			double fontSize = 0;
			string fontFamily = null;
			global::Android.Graphics.Color defaultColor = global::Android.Graphics.Color.Argb(0, 0, 0, 0);
			global::Android.Graphics.Color androidColor = defaultColor;

			Context context = Forms.Context;
			using (var value = new TypedValue())
			{
				if (context.Theme.ResolveAttribute(style, value, true))
				{
					var styleattrs = new[] { global::Android.Resource.Attribute.TextSize, global::Android.Resource.Attribute.FontFamily, global::Android.Resource.Attribute.TextColor };
					using (TypedArray array = context.ObtainStyledAttributes(value.ResourceId, styleattrs))
					{
						fontSize = context.FromPixels(array.GetDimensionPixelSize(0, -1));
						fontFamily = array.GetString(1);
						androidColor = array.GetColor(2, defaultColor);
					}
				}
			}

			if (fontSize > 0)
				result.Setters.Add(new Setter { Property = Label.FontSizeProperty, Value = fontSize });

			if (!string.IsNullOrEmpty(fontFamily))
				result.Setters.Add(new Setter { Property = Label.FontFamilyProperty, Value = fontFamily });

			if (androidColor != defaultColor)
			{
				result.Setters.Add(new Setter { Property = Label.TextColorProperty, Value = Color.FromRgba(androidColor.R, androidColor.G, androidColor.B, androidColor.A) });
			}

			return result;
		}

		void UpdateStyles()
		{
			_dictionary[Device.Styles.BodyStyleKey] = new Style(typeof(Label)); // do nothing, its fine
			_dictionary[Device.Styles.TitleStyleKey] = GetStyle(global::Android.Resource.Attribute.TextAppearanceLarge);
			_dictionary[Device.Styles.SubtitleStyleKey] = GetStyle(global::Android.Resource.Attribute.TextAppearanceMedium);
			_dictionary[Device.Styles.CaptionStyleKey] = GetStyle(global::Android.Resource.Attribute.TextAppearanceSmall);
			_dictionary[Device.Styles.ListItemTextStyleKey] = GetStyle(global::Android.Resource.Attribute.TextAppearanceListItem);
			_dictionary[Device.Styles.ListItemDetailTextStyleKey] = GetStyle(global::Android.Resource.Attribute.TextAppearanceListItemSmall);
		}
	}
}