ListView, TileView and Table

  • All collections widgets support virtualization: gameobjects created only for the visible items.

  • Different ListView, TileView and Table can display the same list.

  • Table Header provides Table specific methods.

  • In most cases ToggleGroup and SwitchGroup components used by widgets under DefaultItem hierarchy should be placed outside DefaultItem gameobject. And on value changed callbacks should process all items, not only the current one, since invisible items do not receive callbacks because of the virtualization.

List View Type

../_images/ListView-fixed-size.png

ListView with Fixed Size.

../_images/ListView-variable-size.png

ListView with Variable Size.

../_images/ListView-ellipse.png

ListView with Ellipse layout.

../_images/TileView-fixed-size.png

TileView with Fixed Size.

../_images/TileView-variable-size.png

TileView with Variable Size.

../_images/TileView-staggered.png

TileView Staggered.

ListView.Container settings for the Ellipse type

  • RectTransform.pivot

    Defines on which side or corner will be the center point.

  • EasyLayout.Ellipse settings

    Width and height usually should be specified, set the same value for the circle.

  • Angle Start

    Base rotation for the first item.

  • Angle Step Auto

    Should be disabled.

  • Angle Step

    Angular distance between items.

  • Fill

    Should be Arc.

  • Arc Length

    Should be 180 if center at the side and 90 if center at the corner.

Options

  • Interactable bool

    Allow users interact with the ListView.

  • Virtualization bool

    Enable virtualization. If enabled GameObject instantiated only for the visible items; otherwise for the all items.

  • List Type ListViewType

    Determines how items are displayed.

    • ListViewWithFixedSize

      Works with EasyLayout, Horizontal Layout Group and Vertical Layout Group.

    • ListViewWithVariableSize

      Works with EasyLayout, Horizontal Layout Group and Vertical Layout Group.

    • ListViewEllipse

      Works with EasyLayout.

    • TileViewWithFixedSize

      Works with EasyLayout.

    • TileViewWithVariableSize

      Works with EasyLayout.

    • TileViewStaggered

      Works with EasyLayout.

  • Sort bool deprecated

    If enabled items will be sorted with SortFunc. Deprecated, replaced with DataSource.Comparer.

  • SortFunc Func<IEnumerable<TItem>, IEnumerable<TItem>> deprecated

    Not available in the Inspector window Function to sort items. Deprecated, replaced with DataSource.Comparer.

  • Data Source ObservableList<TItem>

    List of the items. It works the same way as List<T> with some additions.
    Not available in the inspector window if type not specified as serializable.
  • Multiple Select bool

    Allow to select multiple items, otherwise only one.

  • SelectedIndex int

    Index of the last selected item.

  • SelectedIndices List<int>

    Not available in the Inspector window List of the selected items indices.

  • SelectedItem TItem

    Not available in the Inspector window Last selected item.

  • SelectedItems List<TItem>

    Not available in the Inspector window List of the selected items.

  • Direction ListViewDirection

    ListView direction.

    • Horizontal

    • Vertical

  • DefaultItem TComponent

    A prefab used to display item.

  • Container Transform

    The container of the instantiated gameobjects used to display items. Should have layout required for the specified List Type.

  • ScrollRect ScrollRect

    ScrollRect used by ListView. Required for virtualization support.

  • AllowColoring bool

    Change colors of the highlighted and selected items.
    If you want to more precise control on item colors, like different colors depending of item data, then you can override StateDefault(), StateHighlighted(), StateSelected() methods of item component class.
  • Colors

    Colors for the text and background elements of the DefaultItem instances.

    Text and background elements defined with GraphicsForeground and GraphicsBackground properties of the TComponent.

    • Default Color Color

    • Default Background Color Color

    • Highlighted Color Color

    • Highlighted Background Color Color

    • Selected Color Color

    • Selected Background Color Color

    • Disabled Color Color: multiplicator, actual color is current color (default, highlighted, selected) * disabled Color.

  • Fade Duration float

    Time for a smooth color change when the state of an element changes.

  • End Scroll Delay float

    Delay from last scroll event to OnEndScrolling event raising.

  • Navigation bool

    Allow to use navigation with keyboard or gamepad.

  • Looped List bool

    Is list looped? First items will be displayed after the last item and scrolling scrolling are infinite. Recommended to disable scrollbar.

  • Is Table bool

    Is ListView will be displayed as a table? Used for correct styles support.

  • Set Content Size Fitter bool

    Changes ContentSizeFitter settings according to the selected direction. Disable if you want to use manual settings.

  • Scroll Unscaled Time bool

    Specify time type used by scroll animation.
    If enabled then will be used Time.unscaledTime; otherwise will be used Time.time.
  • Scroll Movement AnimationCurve

    Animation curve for the ScrollTo functions.
    Specify how long scroll animation will be and what speed will it have.
  • Center The Items bool

    Display items at the center of the list if items not enough to fill the list.

  • Precalculate Item Size bool

    Precalculate items sizes for List Type with items of variable size.

    You can disable this option to increase performance in exchange to less accurate scrolling.

  • Auto Scroll Area float

    ListView will be automatically scrolled if the pointer in less then a specified distance from the border during drag&drop.

  • Auto Scroll Speed float

    Speed of auto-scroll.

  • Can Select Func<int, bool>

    The function that determines whether the item with the specified index can be selected. Unselectable items cannot be highlighted and skipped by keyboard and gamepad navigation.

  • Can Deselect Func<int, bool>

    The function that determines whether the item with the specified index can be deselected.

  • Scroll Inertia Until Item Center bool

    Enable custom scroll inertia.
    It is replace ScrollRect inertia in such a way so that after the end of scrolling the item will be exactly in the center.
    Intended to use with ListViewEllipse but works with other types too.
  • Scroll Inertia AnimationCurve

    Similar to Scroll Movement, but only for the scroll inertia.

Events

  • OnSelect UnityEvent<int, ListViewItem>

    The event raised when item selected.

    Arguments: index of the selected item and DefaultItem instance for the selected item.

  • OnDeselect UnityEvent<int, ListViewItem>

    The event raised when item deselected.

    Arguments: index of the deselected item and DefaultItem instance for the deselected item.

  • OnSelectObject UnityEvent<int>

    The event raised when item selected.

    Arguments: index of the selected item.

  • OnDeselectObject UnityEvent<int>

    The event raised when item deselected.

    Arguments: index of the deselected item.

  • OnStartScrolling UnityEvent

    The event raised when scrolling starts.

  • OnEndScrolling UnityEvent

    The event raised when after End Scroll Delay from left last scroll event.

  • onSubmit UnityEvent

    The event raised when ListView gameobject has been selected via a “submit” key you specify (default is the return key).

  • onCancel UnityEvent

    The event raised when ListView gameobject has been deselected.

  • onItemSelect UnityEvent

    The event raised when ListView item gameobject has been selected via a “submit” key you specify (default is the return key).

  • onItemCancel UnityEvent

    The event raised when ListView item gameobject has been deselected.

  • OnUpdateView UnityEvent

    The event raised when ListView view was updated.

  • OnFocusIn UnityEvent<BaseEventData>

    The event raised when ListView gameobject received focus.

  • OnFocusOut UnityEvent<BaseEventData>

    The event raised when ListView gameobject lost focus.

  • OnPointerEnterObject UnityEvent<int>

    The event raised when pointer entered on ListView item gameobject.

    Arguments: index of the item.

  • OnPointerExitObject UnityEvent<int>

    The event raised when pointer exited on ListView item gameobject.

    Arguments: index of the item.

  • OnDataSourceChanged UnityEvent<ListViewCustom<TComponent, TItem>>

    The event raised when DataSource replaced with the new list.

    Arguments: ListView instance.

Items Events

It is ListView.ItemsEvents field with list of items events. First argument is item index, second is item component instance, third is event data.

  • PointerClick UnityEvent<int, ListViewItem, PointerEventData>

    The event raised on every pointer click on item component.

  • FirstClick UnityEvent<int, ListViewItem, PointerEventData>

    The event raised on first pointer click with left mouse button on item component.

  • DoubleClick UnityEvent<int, ListViewItem, PointerEventData>

    The event raised on second pointer click with left mouse button on item component.

  • PointerUp UnityEvent<int, ListViewItem, PointerEventData>

    The event raised on pointer up on item component.

  • PointerDown UnityEvent<int, ListViewItem, PointerEventData>

    The event raised on pointer down on item component.

  • PointerEnter UnityEvent<int, ListViewItem, PointerEventData>

    The event raised on pointer enter on item component.

  • PointerExit UnityEvent<int, ListViewItem, PointerEventData>

    The event raised on pointer exit on item component.

  • Move UnityEvent<int, ListViewItem, AxisEventData>

    The event raised on move with keyboard or gamepad on item component.

  • Submit UnityEvent<int, ListViewItem, BaseEventData>

    The event raised on submit on item component.

  • Cancel UnityEvent<int, ListViewItem, BaseEventData>

    The event raised on cancel on item component.

  • Select UnityEvent<int, ListViewItem, BaseEventData>

    The event raised when item component has been selected by EventSystem.

  • Deselect UnityEvent<int, ListViewItem, BaseEventData>

    The event raised when item component has been deselected by EventSystem.

  • Resize UnityEvent<int, ListViewItem, Vector2>

    The event raised when item component size was changed.

ListViewComponent Class

Component to display item.

Fields and properties

  • Index int

    Index of the displayed item. Negative if item not displayed or not used by ListView.

  • Owner ListViewBase

    Reference to ListView.

  • GraphicsForeground Graphic[]

    References to the foreground objects like Text.

  • GraphicsBackground Graphic[]

    References to the background objects.

Methods

  • SetData(TItem item)

    Set data.

  • GraphicsColoring(Color foregroundColor, Color backgroundColor, float fadeDuration)

    Called by ListView to set colors for the GraphicsForeground and GraphicsBackground.

  • MovedToCache()

    Called by ListView when GameObject moved to cache or recycled.

  • StateDefault()

    Called by ListView when item in the default state.

  • StateSelected()

    Called by ListView when item selected.

  • StateHighlighted()

    Called by ListView when item highlighted.

Auto-Resize DefaultItem instances on ListView Resize Maintaing Aspect Ratio

  • DefaultItem.RectTransform anchors should be set to the horizontal or vertical stretch depending on ListView.Direction

  • Add Aspect Ratio Fitter to the DefaultItem and set Aspect Mode = Width Controls Height or Height Controls Width depending on ListView.Direction

  • Change ListView.ListType to List View With Variable Size or Tile View With Variable Size

  • Make sure that ListView.Container.EasyLayout children size set to Do Nothing.

Multiple DefaultItems

ListView has the TemplateSelector property, it allow to use of different templates depending on the item or index.

namespace UIWidgets.Examples
{
   using UnityEngine;

   public class TreeViewMultipleDefaultItems : MonoBehaviour, IListViewTemplateSelector<TreeViewSampleComponent, ListNode<ITreeViewSampleItem>>
   {
      [SerializeField]
      protected TreeViewSample TreeView;

      [SerializeField]
      protected TreeViewSampleComponentContinent ContinentTemplate;

      [SerializeField]
      protected TreeViewSampleComponentCountry CountryTemplate;

      protected virtual void Start()
      {
         TreeView.TemplateSelector = this;
      }

      public TreeViewSampleComponent[] AllTemplates()
      {
         return new TreeViewSampleComponent[] { ContinentTemplate, CountryTemplate };
      }

      public TreeViewSampleComponent Select(int index, ListNode<ITreeViewSampleItem> item)
      {
         if (item.Node.Item is TreeViewSampleItemContinent)
         {
            return ContinentTemplate;
         }

         return CountryTemplate;
      }
   }
}

IListViewTemplateSelector Interface

Methods:

  • TComponent[] AllTemplates()

    Get all possible templates.

  • TComponent Select(int index, TItem item);

    Returns template to use for specified item with index.

DefaultItem Instances

// also available .Active and .Cache modes
foreach (var instance in ListView.GetComponentsEnumerator(PoolEnumeratorMode.All))
{
   // do somethind with DefaultItem instance
}

Add Item

var new_item = new ListViewIconsItemDescription()
{
   Icon = sampleIcon,
   Name = "test item",
};
listView.DataSource.Add(new_item);

Get Items

var items = listView.DataSource;

Set Items

var items = new ObservableList<ListViewIconsItemDescription>();
listView.DataSource = items;

var items2 = new List<ListViewIconsItemDescription>();
listView.DataSource = items2.ToObservableList();

Display Same List with ListView, TileView or Table

var items = new ObservableList<ListViewIconsItemDescription>();
listView.DataSource = items;
tileView.DataSource = items;
table.DataSource = items;

Get Last Selected Index

Debug.Log(listView.SelectedIndex);

Get Selected Indices

var indices = listView.SelectedIndices;
Debug.Log(string.Join(", ", indices.ConvertAll(x => x.ToString()).ToArray()));

Last Selected Item

Debug.Log(listView.SelectedItem.Name);

Get Selected Items

var selected_items = listView.SelectedItems;
Debug.Log(string.Join(", ", selected_items.ConvertAll(x => x.Name).ToArray()));

Delete Specified Item

listView.DataSource.Remove(items[0]);

Delete Item by Index

listView.DataSource.RemoveAt(0);

Clear List

listView.DataSource.Clear();

Add Items

var new_items = new List<ListViewIconsItemDescription>()
{
   new_item,
   new_item,
   new_item,
};
listView.DataSource.AddRange(new_items);

Optimization

// Use BeginUpdate() and EndUpdate() to keep widget from updating on each change.
// All changes after BeginUpdate() call will be displayed with EndUpdate() call.
var items = listView.DataSource;
items.BeginUpdate();

items.Clear();
items.Add(new_item);
items.Add(new_item);
items.Add(new_item);
items.AddRange(new_items);
items.RemoveAt(0);

// widget will be updated after EndUpdate() call
items.EndUpdate();

Replace Item

listView.DataSource[0] = new ListViewIconsItemDescription()
{
   Name = "new item"
};

Sort

// Sort by LocalizedName or Name in ascending order
Comparison<ListViewIconsItemDescription> ItemsComparisonAsc = (x, y) => x.Name.CompareTo(y.Name);

// sort by LocalizedName or Name in descending order
Comparison<ListViewIconsItemDescription> ItemsComparisonDesc = (x, y) => -(x.Name).CompareTo(y.Name);

// sort items only once
items.Sort(ItemsComparisonAsc);

Enable Permanent Sort

items.Comparison = ItemsComparisonDesc;

Important

Items will be always sorted, but if you use .BeginUpdate() then items will be re-sorted only after .EndUpdate() call.

Disable Permanent Sort

items.Comparison = null;

Set Selected Index

listView.SelectedIndex = 1;

Or:

listView.Select(1);

Behavior is different if you enable MultipleSelect:

  • listView.SelectedIndex = 1 last selected item will be deselected and specified item will be selected.

  • listView.Select(1) new item will be added to selected items.

Deselect

listView.SelectedIndex = -1;

Or:

listView.Deselect(1);

Adding Callbacks to Custom Events of the Components

public class YourListView : ListViewCustom<YourListViewItemComponent, YourListViewItem>
{
    protected override void AddCallback(ListViewItem item)
    {
        base.AddCallback(item);
        item.onDoubleClick.AddListener(ProcessDoubleClick);
    }

    protected override void RemoveCallback(ListViewItem item)
    {
        base.RemoveCallback(item);
        item.onDoubleClick.RemoveListener(ProcessDoubleClick);
    }

    void ProcessDoubleClick(int index)
    {
        Debug.Log("double click: " + DataSource[index]);
    }
}

Scroll to Item

listView.ScrollToAnimated(index);

Disable Items

protected virtual void Start()
{
   listView.CanSelect = CanBuy;
}

bool CanBuy(Item item)
{
   return player.Money >= item.Price;
}

Example of ListView with Filter

namespace UIWidgets.Examples
{
   using System.Collections.Generic;
   using UIWidgets;
   using UnityEngine;
   using UnityEngine.Serialization;

   /// <summary>
   /// Sample ListViewIcons with filter.
   /// </summary>
   public class ListViewIconsWithFilter : ListViewIcons
   {
      [SerializeField]
      List<ListViewIconsItemDescription> listItems = new List<ListViewIconsItemDescription>();

      ObservableList<ListViewIconsItemDescription> originalItems;

      /// <summary>
      /// Get or sets items.
      /// </summary>
      public ObservableList<ListViewIconsItemDescription> OriginalItems
      {
         get
         {
            if (originalItems == null)
            {
               originalItems = new ObservableList<ListViewIconsItemDescription>(listItems);
               originalItems.OnChange += Filter;
            }

            return originalItems;
         }

         set
         {
            if (originalItems != null)
            {
               originalItems.OnChange -= Filter;
            }

            originalItems = value;

            if (originalItems != null)
            {
               originalItems.OnChange += Filter;
            }
         }
      }

      /// <summary>
      /// Search string.
      /// </summary>
      protected string Search = string.Empty;

      /// <summary>
      /// Filter data using specified search string.
      /// </summary>
      /// <param name="search">Search string.</param>
      public void Filter(string search)
      {
         Search = search;
         Filter();
      }

      /// <summary>
      /// Copy items from OriginalItems to DataSource if it's match specified string.
      /// </summary>
      protected void Filter()
      {
         DataSource.BeginUpdate();
         DataSource.Clear();

         if (string.IsNullOrEmpty(Search))
         {
            // if search string not specified add all items
            DataSource.AddRange(OriginalItems);
         }
         else
         {
            // else add items with name starts with the specified string
            var finded = OriginalItems.FindAll(x => x.Name.StartsWith(Search));
            DataSource.AddRange(finded);
         }

         DataSource.EndUpdate();
      }

      /// <summary>
      /// Init this instance.
      /// </summary>
      public override void Init()
      {
         base.Init();

         // call Filter() to set initial DataSource
         Filter();
      }

      /// <summary>
      /// Process the destroy event.
      /// </summary>
      protected override void OnDestroy()
      {
         if (originalItems != null)
         {
            originalItems.OnChange -= Filter;
         }

         base.OnDestroy();
      }
   }
}