Creating a List with a default selection

28 views
Skip to first unread message

Holger Codeman

unread,
Oct 23, 2017, 4:01:07 AM10/23/17
to Kivy users support
Hi all,

I have a problem to understand how to create a ListView with a default selected Button. I managed to create the ListView and to react on key pressing, but I need a selected item at program start (ideally this selection by program code triggers a "on_press" of this item). I have searched and tried a lot but nothing worked.

Perhaps anyone can point me to an example? If not, I can try to create a small version of my current problem...

Is ListView and ListAdapter the right way? I read something about it's depreciated and I should use RecycleView?

TIA, Holger

Daniel Lim

unread,
Oct 25, 2017, 7:46:10 PM10/25/17
to Kivy users support

To set a default selected Button in ListView, put the following as arguments to the ListAdapters. Please refer to the example below for details. ListView has been deprecated since Kivy version 1.10.0

Snippet
selection_mode='single',
allow_empty_selection=False,

Example
from kivy.uix.listview import ListView, ListItemButton
from kivy.adapters.listadapter import ListAdapter
from kivy.adapters.models import SelectableDataItem
from kivy.base import runTouchApp


class DataItem(SelectableDataItem):
def __init__(self, text="", is_selected=False):
self.text = text
self.is_selected = is_selected


data_items = [DataItem(text="cat"),
DataItem(text="dog"),
DataItem(text="frog")]


def list_items_args_converter(row_index, obj):
return {'text': obj.text,
'size_hint_y': None,
'height': 25}

list_adapter = ListAdapter(data=data_items,
args_converter=list_items_args_converter,
propagate_selection_to_data=True,
selection_mode='single',
allow_empty_selection=False,
cls=ListItemButton)

list_view = ListView(adapter=list_adapter)


runTouchApp(list_view)


Output

Holger Codeman

unread,
Oct 26, 2017, 1:58:15 AM10/26/17
to Kivy users support

Hi Daniel,

many thanks for this nice explanation!!! I was searching exactly for this and found nothing... I will try this soon!

Regards, Holger
Reply all
Reply to author
Forward
0 new messages