我想在C#代码中以编程方式设置一些小部件的颜色,但是当它们在我的应用程序主题中设置并且在白天/晚上模式下不同时,我不知道如何获取颜色。
到目前为止,我所拥有的:
attrs.xml:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
<declare-styleable name="MyThemeColors">
<attr format="color" name="colorOkay"/>
<attr format="color" name="colorOnOkay"/>
<attr format="color" name="colorWarning"/>
<attr format="color" name="colorOnWarning"/>
</declare-styleable>
</resources>在我的themes.xml中,这些颜色设置如下
<item name="colorWarning">@color/color_warning</item>其中colorWarning是在color.xml中定义的,不同于day和nicht模式。对colorSurface等也是如此。这可以很好地工作。
为了在C#代码中获得colorWarning的颜色,我尝试了:
Context context = Android.App.Application.Context;
TypedArray ta = context.Theme.ObtainStyledAttributes(Resource.Styleable.MyThemeColors);
var colorWarning = ta.GetColorStateList(Resource.Styleable.MyThemeColors_colorWarning);
ta.Recycle();但colorWarnig始终为空。
我也试过了
Android.App.Application.Context.GetColor(...)但这似乎对Android.Resource.Color有效...仅限颜色,不适用于MyAppNamespace.Resource.Color....颜色。
发布于 2021-03-11 13:24:54
Xamarin.Forms应用程序可以通过使用带有AppThemeBinding标记扩展以及SetAppThemeColor和SetOnAppTheme<T>扩展方法的资源来响应系统主题更改。
您可以使用下面的代码来更改不同于白天/夜间模式的颜色。
Label label = new Label();
label.SetAppThemeColor(Label.TextColorProperty, Color.Green, Color.Red);有关更多详细信息,您可以查看代码示例中的MS文档。https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/theming/system-theme-changes#react-to-theme-changes
更新:
黑暗主题在Android 10 (API级别29)和更高版本中可用。
1.您可以在 AndroidManifest.xml**.**中更改AppTheme
更改:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>至:
<style name="AppTheme" parent="Theme.AppCompat.DayNight">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>并在MainActivity中设置主题:
[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]2.您可以通过编程方式更改主题。
删除ActivityAttribute中的Theme = "@style/AppTheme"。
在Styles.xml中创建另一个AppTheme2。
<style name="AppTheme2" parent="Theme.AppCompat.DayNight">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>在OnCreate()方法中添加代码。请注意,在加载布局之前调用SetTheme。
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetTheme(Resource.Style.AppTheme2);
SetContentView(Resource.Layout.activity_main);
}https://stackoverflow.com/questions/66565847
复制相似问题