Listview Selected Item Background Color

ChrisgozdChrisgozd USMember ✭✭

Is it possible to set the ListView selected item background color? Right now on IOS its gray and I want it to be transparent if possible.

Posts

  • ChrisgozdChrisgozd USMember ✭✭

    Still haven't found a solution to this..

  • ChrisgozdChrisgozd USMember ✭✭

    Nice, i'll have to try it out! Do you know of a similar renderer for Android? And do you know what type of cell a listview item is?

  • ThorstenBentrupThorstenBentrup DEMember ✭✭

    Sorry, but for Android I have not yet a solution.

    I think one has to use a ListViewRenderer, but this is currently 'internal'...

  • BrianRepettiBrianRepetti USUniversity ✭✭✭

    Is there no way to set the selected item properties for Android & WinPhone?

    Should I create a new Renderer that implements the native list on each platform instead? Or is there a way to extend the existing ListView?

    Having trouble finding any documentation on the subject.

  • DemiVisionDemiVision USMember ✭✭

    I posted a solution here that seems to work well on both iOS and Android and is entirely cross-platform with no custom renderers:

    stackoverflow.com/a/26896715/4216951

  • HrishiDHrishiD INMember ✭✭
    edited October 2015

    class CustomListViewCellRenderer : ViewCellRenderer
    {

        public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
        {
            var cell = base.GetCell(item, reusableCell, tv);
    
            cell.SelectionStyle = UITableViewCellSelectionStyle.None;
    
    
            return cell;           
    
        }
    
    
    }
    

    This is for iOS

  • AdrianKnightAdrianKnight USMember ✭✭✭✭

    @MarianGieseler This is a life saver. I'd been searching online for a solution for hours. :)

  • In case of Android I tried this..

    on your ListView ItemSelected event handler, you can do:

    listview.ItemSelected = null;

    while in case of iOs
    I wrote CustomListViewCellRenderer as suggested above and it works fine for me..

  • JulienRosenJulienRosen CAMember ✭✭✭✭

    With MVVM, make your ItemTemplate have a binding to a colour, then change the colour when the selected item changes.

  • voidvoid DKBeta ✭✭✭

    Anyone knows why UITableViewCellSelectionStyle in CustomListViewCellRenderer dont work anymore? Running 2.0.1.6505

  • MichaelRidlandMichaelRidland AUInsider, University ✭✭✭

    @void Same problem, did you solve it?

  • voidvoid DKBeta ✭✭✭

    @MichaelRidland I'm afraid not.

  • AlanSpiresAlanSpires USBeta ✭✭

    Setting the tableview to AllowsSelection = false seems to have the desired effect while still allowing the listviews ItemTapped to fire

  • dengerelidengereli TRMember ✭✭

    i have many issues UWP, one of them this. and i never find any solution (its out of subjectt)

    selected item backround color has issue on differennt machine (not different platform) which is Windows 10.
    and no way to change color?
    and all elements change defaults and nothing display. but item can clickable....
    do you have any solution to change selected item background color? or stoped to platform defaults?

  • akki12087akki12087 INMember

    can give me custom renderer for windows 8.1

  • DonRobbDonRobb USMember ✭✭

    I get an invalid cast when
    var viewCell =(ViewCell)sender;

    executes

  • MayurKerasiyaMayurKerasiya USMember ✭✭

    @DonRobb
    I am also getting same error

  • PeterFarrerPeterFarrer USMember ✭✭
    edited April 2017

    Michelangelo Franco.

    Amazingly simple, I agree. Don't forget it is the tapped event on the ViewCell not the ListView.

    Unfortunately though the color sticks when another cell is selected.

    Tested on latest pre-release of Xamarin Forms.

  • AMAXAMAX USMember ✭✭

    @MichelangeloFranco said:
    My working solution is like this, without customrender or something else, working in Xamarin Forms Xaml:

    On Xaml:

    On code behind:

    private void Cell_OnTapped(object sender, EventArgs e)
    {
    var viewCell = (ViewCell)sender;
    if (viewCell.View != null)
    {
    viewCell.View.BackgroundColor = Color.Red;
    }
    }

    easy pease.

    Not tested on Windows Phone.

    sometimes worked, and sometimes not work. any update to this code?

  • Lang_tu_bi_dienLang_tu_bi_dien VNMember ✭✭
    edited October 2017

    When i set ListViewCachingStrategy cachingStrategy is RecycleElement . All select are disable.
    I just found the way to fix IOS.

     protected override void OnElementChanged(ElementChangedEventArgs<ListView> e)
            {
                base.OnElementChanged(e);
                if (Control != null && e != null )
                {
                    Control.Delegate = new ListViewDelegate(e.NewElement);
                }
            }
    
    
     class ListViewDelegate : UITableViewDelegate
            {
                private ListView _listView;
    
            internal ListViewDelegate(ListView listView)
            {
                _listView = listView;
            }
    
            public override void WillDisplay(UITableView tableView, UITableViewCell cell, Foundation.NSIndexPath indexPath)
            {
                cell.SelectedBackgroundView = new UIView()
                {
                    BackgroundColor = Color.Red.ToUIColor()
                };
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    _listView = null;
                }
                base.Dispose(disposing);
            }
        }
    

    Hope it help someone!

  • AhmedHasanAhmedHasan USMember ✭✭
    edited October 2017

    Hey It works, Thank you so much @MarianGieseler for Android and @HrishiD for iOS , Hope this help others.

    iOS

    // I use ViewCell because I want to change in All places but if anyone wants to change for a particular listView
    // then you need to make a custom control and inherit it from ViewCell , and use that control in xaml with this renderer

    [assembly: ExportRenderer(typeof(ViewCell), typeof(CustomListViewCellRenderer))]
    namespace your namespace

    class CustomListViewCellRenderer : ViewCellRenderer
    {
    public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
    {
    var cell = base.GetCell(item, reusableCell, tv);
    cell.SelectionStyle = UITableViewCellSelectionStyle.None;
    return cell;
    }
    }

    Android:

    Just put this in your custom theme:

    "@android:color/transparent"

    if you need for particular listView in Android then you will need a renderer for this also

    Thanks
    Ahmed Hasan

  • AhmedHasanAhmedHasan USMember ✭✭

    Hey It Works.. Thanks you so much @MarianGieseler for Android and @HrishiD for iOS . Hope it helps someone.

    iOS

    // I applied on All ViewCell because I need it, if anyone wants to apply for a particular ListView then you need to make
    // a CustomControl for this which Inherit from ViewCell and use this control in xaml with this renderer in iOS

    [assembly: ExportRenderer(typeof(ViewCell), typeof(CustomListViewCellRenderer))]
    namespace YourApp.iOS
    {
    public class CustomListViewCellRenderer : ViewCellRenderer
    {
    public override UIKit.UITableViewCell GetCell(Xamarin.Forms.Cell item, UIKit.UITableViewCell reusableCell, UIKit.UITableView tv)
    {
    //return base.GetCell(item, reusableCell, tv);
    var cell = base.GetCell(item, reusableCell, tv);
    cell.SelectionStyle = UITableViewCellSelectionStyle.None;
    return cell;
    }
    }
    }

    Android

    Just put this in your custom theme:
    @android:color/transparent

    Just to Apply in all places, if you want for a particular list then you need to Create CustomControl and a renderer

  • LouisTaljaardLouisTaljaard ZAMember ✭✭

    @Lang_tu_bi_dien said:
    When i set ListViewCachingStrategy cachingStrategy is RecycleElement . All select are disable.

    Hi , I have the same problem, when I set the caching strategy to something other than the default this approach does not work anymore. I'd like to try your suggestion. On which class should the OnElementChanged method go?

  • LouisTaljaardLouisTaljaard ZAMember ✭✭

    @Lang_tu_bi_dien thank you, your suggestion works even with a non-standard cachingStrategy (the OnElementChanged must be on a custom iOS ListView Renderer class). I prefer this to having code in the OnItemSelected method coupled with a binding from the ViewModel for the background color.

    The final code then looks like this:

    Xamarin.Forms code:

    namespace MyProject
    {
    public class ListView2 : ListView
    {
    public ListView2(ListViewCachingStrategy cachingStrategy) : base(cachingStrategy)
    {
    }
    }
    }

    XAML on your page:

    <ListView.ItemTemplate>


    <ViewCell.View>

    iOS-specific renderer:

    [assembly: ExportRenderer(typeof(ListView2), typeof(ListView2Renderer))]
    namespace MyProject.iOS
    {
        class ListView2Delegate : UITableViewDelegate
        {
            private ListView _listView;
    
            internal ListView2Delegate(ListView listView)
            {
                _listView = listView;
            }
    
            public override void WillDisplay(UITableView tableView, UITableViewCell cell, Foundation.NSIndexPath indexPath)
            {
                cell.SelectedBackgroundView = new UIView()
                {
                    BackgroundColor = Color.Red.ToUIColor()
                };
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    _listView = null;
                }
                base.Dispose(disposing);
            }
        }
    }
    
  • Lang_tu_bi_dienLang_tu_bi_dien VNMember ✭✭
    edited November 2017

    @LouisTaljaard
    Easy to implement itemSelected.

    Just override method "RowSelected()" on UITableViewDelegate.

     public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
            {
                listView.SelectedItem = listView.ItemsSource.ElementAt(indexPath.Row);
            }
    
  • LouisTaljaardLouisTaljaard ZAMember ✭✭

    @Lang_tu_bi_dien thanks again. How do you do the selected item background color on Android? I'm looking at that now but haven't found a nice way to do it yet.

  • Lang_tu_bi_dienLang_tu_bi_dien VNMember ✭✭

    @LouisTaljaard I try a lot but i didn't find the solution.
    I still not work on xamarin project. So i can't help you at this time.

  • TimoSchmidtTimoSchmidt DEMember ✭✭
    edited November 2017

    Sorry to ask, but how would I show the user which TextCell in a Xamarin.Forms.ListView is currently selected?

    I can programmatically select an item by

    MyListView.SelectedItem = SomeTextCell;
    

    But that doesn't highlight this item's backcolor.
    The item is only highlighted when I tap on it.

    Is that really the intended behaviour?

  • EhsanJahanagiriEhsanJahanagiri USMember ✭✭

    for android platform according to
    https://blog.wislon.io/posts/2017/04/11/xamforms-listview-selected-colour

    class CustomViewCellRenderer : Xamarin.Forms.Platform.Android.ViewCellRenderer
        {
            private Android.Views.View _cellCore;
            private bool _selected;
            protected override Android.Views.View GetCellCore(Cell item,
                                                          Android.Views.View convertView,
                                                          ViewGroup parent,
                                                          Context context)
            {
                _cellCore = base.GetCellCore(item, convertView, parent, context);
                _selected = false;
                return _cellCore;
            }
    
            protected override void OnCellPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs args)
            {
                base.OnCellPropertyChanged(sender, args);
                if (args.PropertyName == "IsSelected")
                {
                    _selected = !_selected;
                    var extendedViewCell = sender as ViewCell;
                    if (_selected)
                        _cellCore.SetBackgroundColor(Android.Graphics.Color.WhiteSmoke);
                    else
                        _cellCore.SetBackgroundColor(Android.Graphics.Color.Transparent);
                }
            }
        }
    
  • JohnWilson.4976JohnWilson.4976 AUMember ✭✭
    edited May 2018

    @EhsanJahanagiri I'm sorry but the implementation described in that blog post was broken across all listview caching strategies recently, with all the .net standard/xamarin forms updates. Tho it was just built with RetainElement in mind...

    I think I have it resolved now, for Android (using RecycleElement), but not yet for iOS. I've been chasing my tail on this for weeks. There's a branch in that github repo called fix-listview-demo, which appears to fine for Android. iOS is still broken tho... I can't believe it's this hard! Maybe that's why the xamarin forms guys haven't implemented it yet :wink:

  • Damien_DoumerDamien_Doumer Member ✭✭
  • KishanRathodKishanRathod University

    @MarianGieseler said:
    I reverse the ListViewRenderer and found in CellAdapter.cs a static resource id 16843664.
    In Android Documentation http://developer.android.com/reference/android/R.attr.html you can find this constant definition!

    Just put this in your custom theme:
    <item name="android:colorActivatedHighlight">@android:color/transparent</item>

    I know this is an old post but it works for Android. My build failed at first but it worked after doing Clean Solution and Rebuild. Thanks @MarianGieseler :)

  • AmigomanAmigoman Member ✭✭

    @KishanRathod

    How exactly do I create a custom theme? In which file do I need to add that line of code?

  • MREmeMREme Member ✭✭

    This article by Venkata Swamy Balaraju appears to answer the question (though I have not tried it).

    https://www.c-sharpcorner.com/article/how-to-change-listview-selecteditem-bg-color-in-xamarin-forms/

    However, this seems like just way too much work for such a seemingly simple thing. I am wondering if this will ever be implemented into Xamarin.Forms?

  • JanmandenJanmanden Member

    ^ Well, the problem with iOS and SelectedBackgroundView revolves around using any other CachingStrategy than RetainElement and since that article doesn't even use CachingStrategy at all it resolves nothing other than being a nice guide on how to do it all before that pivotal moment of agony.

  • stesvisstesvis USMember ✭✭✭

    I still can't believe that in 2019 there is not a property in ListView to set the highlighted background color.
    Do we still need renderers?

Sign In or Register to comment.