8

We have an app that has customizable colors. This makes the orange Android default for selected items in a list view look pretty bad sometimes. We want to change the color of a listview's selected item.

I know how to do this in the code behinds (xaml.cs) for our pages and I'm aware you can statically change it in the styles.xml. But because the listview color can change, we could be left with a similar issue with whatever color we pick.

Is there a way to access and change the styles.xml values from code?

2 Answers2

0

You can do it with Xamarin Themes has a clear tutorial on how to do it.

Then You can use the following to change themes

void OnPickerSelectionChanged(object sender, EventArgs e)
{
    Picker picker = sender as Picker;
    Theme theme = (Theme)picker.SelectedItem;

    ICollection<ResourceDictionary> mergedDictionaries = Application.Current.Resources.MergedDictionaries;
    if (mergedDictionaries != null)
    {
        mergedDictionaries.Clear();

        switch (theme)
        {
            case Theme.Dark:
                mergedDictionaries.Add(new DarkTheme());
                break;
            case Theme.Light:
            default:
                mergedDictionaries.Add(new LightTheme());
                break;
        }
    }
}

UPDATE:

If you want to change the selection on android you'll have to do it in your android styles.xml file, to change it dynamically you'll have to write an affect :

<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <color name="DarkYellow">#FF00FF</color>
  <style name="Theme.MyHoloLight" parent="android:Theme.Holo.Light">
    <item name="android:colorPressedHighlight">@color/DarkYellow</item>
    <item name="android:colorLongPressedHighlight">@color/DarkYellow</item>
    <item name="android:colorFocusedHighlight">@color/DarkYellow</item>
    <item name="android:colorActivatedHighlight">@color/DarkYellow</item>
    <item name="android:activatedBackgroundIndicator">@color/DarkYellow</item>
  </style>
</resources>
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
LeRoy
  • 4,189
  • 2
  • 35
  • 46
0

We can also create the ViewCell renderer with the Backgroundcolor Bindable property. With that what we can do is to set the required color to the Bindable property into xaml itself and that will set the color in its renderer so we can provide different colors as per requirement.