How to get theme colors programatically - xamarin

I want to set some widget color programmatically in C# code but I cannot figure out how to get the color when they are set in my app theme and differ for day/night mode.
What I have so far:
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>
in my themes.xml this colors are set like
<item name="colorWarning">#color/color_warning</item>
where colorWarning is defined in color.xml, different for day and nicht mode. The same is done for colorSurface and so on. This works fine.
To get the color for colorWarning in C# code I tried:
Context context = Android.App.Application.Context;
TypedArray ta = context.Theme.ObtainStyledAttributes(Resource.Styleable.MyThemeColors);
var colorWarning = ta.GetColorStateList(Resource.Styleable.MyThemeColors_colorWarning);
ta.Recycle();
but colorWarnig is always null.
I also tried
Android.App.Application.Context.GetColor(...)
but this seemt to work for Android.Resource.Color.[...] colors only and not for MyAppNamespace.Resource.Color.[...] colors.

Xamarin.Forms applications can respond to system theme changes by consuming resources with the AppThemeBinding markup extension, and the SetAppThemeColor and SetOnAppTheme<T> extension methods.
You could use the code below to change the color which differ for day/night mode.
Label label = new Label();
label.SetAppThemeColor(Label.TextColorProperty, Color.Green, Color.Red);
For more details, you could check the MS docs with the code sample. https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/theming/system-theme-changes#react-to-theme-changes
Updated:
The Dark theme is available in Android 10 (API level 29) and higher.
1. You could change your AppTheme in AndroidManifest.xml.
Change:
<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>
To:
<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>
And set the Theme in the MainActivity:
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
2. You could change the Theme programmatically.
Delet the Theme = "#style/AppTheme" in ActivityAttribute.
Create another AppTheme2 in Styles.xml.
<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>
Add the code in the OnCreate() method. Please note call the SetTheme before you load the layout.
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);
}

Related

Tabbar stopped showing any modifications made to the Tabbar file in Xamarin->Laoyuts

new here. I need help figuring out why my xamarin project is not reading any of the changes I make to the Tabbar.xml file. Everything was working fine until I decided to add a splash screen style. It could have been something else but that is the only major change I have done to my project, unless I deleted something i wasn't supposed to. Regardless I will be showing those changes as well. I was thinking of just making a custom renderer to avoid this headache, but not I really am curious why this is occurring. Also the unselected tint color has defaulted to white. I can try to change that on the Tabbar.xml side but it does not update. Only the selectedTabcolor changes but because I set that in the <TabbedPage></TabbedPage> itself. All I want is to have the Text color of the unselected tabs to default the grey that the tab icons seem to defult to, that's how it used to be, and set the selectedTabcolor and TabIndicatorColor to the same color which is #008000.
MainActivity
[Activity(Label = "Weather App", Icon = "#mipmap/icon", Theme = "#style/MainTheme", ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.SetTheme(Resource.Style.MainTheme);
base.OnCreate(savedInstanceState);
CrossCurrentActivity.Current.Init(this, savedInstanceState);
Rg.Plugins.Popup.Popup.Init(this);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
SplashScreen
[Activity(Label = "Weather App", Icon = "#mipmap/icon", Theme ="#style/SplashTheme", MainLauncher = true)]
public class SplashActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
var intent = new Intent(this, typeof(MainActivity));
StartActivity(intent);
Finish();
}
}
Styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MainTheme" parent="MainTheme.Base">
<item name="colorPrimary">#efefef</item>
<!-- colorPrimaryDark is used for the status bar -->
<item name="colorPrimaryDark">#008000</item>
<!-- colorAccent is used as the default value for colorControlActivated
which is used to tint widgets -->
<item name="colorAccent">#019501</item>
</style>
<!-- SPLASH SCREEN -->
<style name="SplashTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">#drawable/splash_screen</item>
</style>
</resources>
Tabbar.xml
<android.support.design.widget.TabLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabTextColor="#android:color/black"
app:tabIndicatorHeight="2dp"
app:tabIndicatorColor="#008000"
/>
EDIT: As request here is an image of how my tabbar looks like:
I also removed the SelectedTabColor from the <TabbedPage> itself and added on those changes to the Tabbar.xml and this is the result. I can't get the text color, nor the indicator color nor the selected color to change through the Tabbar. I believe my Tabbar.xaml page is just not being read.
You could define the text color in your Tabbar.xml in the Resources/layout/Tabbar.xml of the androd project.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TabLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabGravity="fill"
app:tabMode="fixed"
app:tabTextColor="#android:color/black" //unselect text color
app:tabIndicatorHeight="2dp"
app:tabSelectedTextColor="#008000"
app:tabIndicatorColor="#008000"
/>
and if you set the UnselectedTabColor or SelectedTabColor in your tabbedpage.xaml,It will overrides the settings in the Tabbar.xml.It has nothing to do with the startup page you added.
If your project has migrated to AndroidX,you could install Xamarin.AndroidX.AppCompat.Resources and Xamarin.Android.Support.Design nugets separately.

Unable to change the navigation Bar Background Color Xamarin forms

I already tried for chnage the Navigation Bar Background Color but its not working.
<ResourceDictionary>
<Style TargetType="NavigationPage">
<Setter Property="BarBackgroundColor" Value="#6eb43a"/>
<Setter Property="BackgroundColor" Value="#6eb43a"/>
</Style>
</ResourceDictionary>
BarBackgroundColor = Not Working
BackgroundColor= Working
so when I am using BackgroundColor(problem is that it change the background color also) then it will effect on Navigation Background but BarBackgroundColor not working.
Have any solution for change the BarBackground Color globally so that it will effect on whole project?
For those using the new Xamarin.Forms.Shell layout, you do this by setting the background color directly on the Shell node
<Shell BackgroundColor="#FFFFFF">...
This will then flow down the hierarchy, which you can override on child nodes as you require.
Try change it from code behind:
MainPage = new NavigationPage(new MainPage())
{
BarBackgroundColor = Color.FromHex("#6eb43a"),
BarTextColor = Color.Black,
};
Try
after InitializeComponent();
((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.White;
OR
((NavigationPage)Application.Current.MainPage).BarBackgroundColor = Color.FromHex("#2196f3");
It will change the navigationbar color of all pages.
You have already written your style in App.Xaml. Now you just have to call that style in your ContentPage xaml file, so that it will set for all the pages.
Style="{DynamicResource NavigationPage}"
Let me know if this helps you.

How to change the color of the menu icon on the MasterPageDetalis xamarin.forms?

I'm creating a project and need to change the menu icon, but I have not found a solution yet. How do I change the color of the menu icon in MasterPageDetalis xamarin.forms?
Change in your base theme from style.xml
<style name="MyTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
<item name="drawerArrowStyle">#style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="#style/Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">#color/green</item>
</style>
Please suggest me if i'm wrong
In the new version of Forms you would change the ActionBar color (and text color) like this:
var navigon = new NavigationPage(new WebViewPage());
navigon.BarBackgroundColor = Color.Teal;
navigon.BarTextColor = Color.White;
If you using MasterDetailPage you use override OnAppearing in your MasterDetailPage it should work.

How to Change Checkbox/Radibutton Color in Xamarin?

I have implemented Radio button and Checkbox control in my application using custom rendering. I have rendered the control by referring the below link. The controls default color is white. Since my application background color is white controls are not visible. I tried to change the color of the controls. But it is not working. Text color only changing. Can anyone suggest how to change the color of Checkbox/Radio button controls?
https://github.com/XLabs/Xamarin-Forms-Labs
Thanks in Advance.
You can set Xamarin.Forms control (like Switch) color from renderer with using below line code in OnElementChanged method:
Control.OnTintColor = Color.Blue.ToUIColor();
for your XLab control, you need to set background color in CheckBoxRenderer and change color in OnElementChanged method. or you can change from control also.
BackgroundColor = Element.BackgroundColor.ToUIColor();
For Android you can manage by material design like:
Create a new style.xml file with this (Change the color in colorAccent to whatever you like) and put it inside the Resources folder.
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<style name="MyTheme" parent="MyTheme.Base">
</style>
<!-- Base theme applied no matter what API -->
<style name="MyTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- colorAccent is used as the default value for colorControlActivated which is used to tint widgets -->
<item name="colorAccent">#0000FF</item>
<!-- You can also set colorControlNormal, colorControlActivated colorControlHighlight and colorSwitchThumbNormal. -->
</style>
</resources>
Then add an attribute to your MainActivity.cs to load that theme.
[Activity(Label = "MyApp", Icon = "#drawable/icon", Theme = "#style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, WindowSoftInputMode = SoftInput.AdjustResize)]
public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity

Custom theme for Android in Xamarin not being found

I am using Visual Studio.
In my MainActivity.cs file I am trying to set a custom theme. The Activity attribute looks like this: [Activity(Label = "MyTest", Icon = "#drawable/icon", Theme = "#android:style/Theme.Idkred", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
When I try and build I am getting: error APT0000: No resource found that matches the given name (at 'theme' with value '#android:style/Theme.Idkred').
I have a values folder in my Android resources folder. In there is a styles.xml file. The styles.xml file's build action is AndroidResource.
It looks like it is getting processed because in the build output I see Processing: obj\Debug\res\values\styles.xml.
My styles.xml file has this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Idkred" parent="#android:style/Theme.Holo.Light">
<item name="android:actionBarItemBackground">#drawable/selectable_background_idkred</item>
<item name="android:popupMenuStyle">#style/PopupMenu.Idkred</item>
<item name="android:dropDownListViewStyle">#style/DropDownListView.Idkred</item>
<item name="android:actionBarTabStyle">#style/ActionBarTabStyle.Idkred</item>
<item name="android:actionDropDownStyle">#style/DropDownNav.Idkred</item>
<item name="android:actionBarStyle">#style/ActionBar.Solid.Idkred</item>
<item name="android:actionModeBackground">#drawable/cab_background_top_idkred</item>
<item name="android:actionModeSplitBackground">#drawable/cab_background_bottom_idkred</item>
<item name="android:actionModeCloseButtonStyle">#style/ActionButton.CloseMode.Idkred</item>
</style>
... (more styles)
</resources>
You have to remove the android: namespace.
[Activity(Label = "MyTest", Icon = "#drawable/icon", Theme = "#style/Theme.Idkred", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
This namespace is only for resources that come from Android it self.

Resources