Reputation: 171
I've implemented dark mode support recently in my Xamarin app following this tutorial : https://devblogs.microsoft.com/xamarin/modernizing-ios-apps-dark-mode-xamarin/
I've set my Label Colors using a Style defined in App.xaml like this :
<Style x:Key="label" TargetType="Label">
<Setter Property="TextColor" Value="{DynamicResource label}"/>
</Style>
<Style x:Key="labelLight" TargetType="Label">
<Setter Property="TextColor" Value="{DynamicResource labelLight}"/>
</Style>
Where the colors label
and labelLight
are defined in a ResourceDictionary
named LightTheme.xaml and DarkTheme.xaml.
I also implemented a custom renderer for iOS like this:
public class ThemeRenderer : Xamarin.Forms.Platform.iOS.PageRenderer
{
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.OldElement != null || Element == null)
return;
SetTheme();
}
public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection)
{
base.TraitCollectionDidChange(previousTraitCollection);
if (TraitCollection.UserInterfaceStyle != previousTraitCollection.UserInterfaceStyle)
SetTheme();
}
private void SetTheme()
{
if (TraitCollection.UserInterfaceStyle == UIUserInterfaceStyle.Dark)
{
App.Current.Resources = new DarkTheme();
App.AppTheme = Theme.Dark;
}
else
{
App.Current.Resources = new LightTheme();
App.AppTheme = Theme.Light;
}
}
}
This is where I get in trouble, my Android version of the App doesn't recognize these colors (everything is in LightGray) and my App doesn't run anymore under iOS 12 and lower. I have no clue what to do to fix this.
Upvotes: 0
Views: 263
Reputation: 14956
For example in android activity
[Activity(Label = "@string/app_name", Theme = "@style/MyTheme", MainLauncher =true)]
public class MainActivity : AppCompatActivity{
...
}
then in your Resources/values/styles.xml :
<!-- Base application theme. -->
<style name="MyTheme" parent="Theme.AppCompat.DayNight.DarkActionBar"> // base theme to use Theme.AppCompat.DayNight
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="android:colorPrimary">#ff29b6f6</item>
</style>
and you could read this.
Upvotes: 0