Search code examples
nativescriptnativescript-telerik-ui

Nativescript: RadListView, how to switch layout (listViewLayout) programatically


I have a very common scenario when the user can switch list layout between linear/grid/staggered view by tapping an icon. Before I had 2 lists - ListView for standard list layout and RadListView for grid view. I hided and showed them depending on required "mode". But since RadListView has all required layouts theoretically I can have only one list and reuse it by switching layouts. I haven't found how to do that directly in XML (that would be the best approach if any), so I'm thinking of doing this programatically in the code behind.

Here is my try:

    function _switchListViewLayout() {
        const list = modal.getViewById( 'list' )
        let layout

        if ( list.listViewLayout instanceof ListViewLinearLayout ) {
            // switch to grid
            layout = new ListViewGridLayout()
            layout.scrollDirection = 'vertical'
            layout.itemHeight = 150
            layout.spanCount = 2
        }

        else if ( list.listViewLayout instanceof ListViewGridLayout ) {
            // switch to list
            layout = new ListViewLinearLayout()
            layout.scrollDirection = 'vertical'
            layout.itemHeight = 66
        }

        list.listViewLayout = layout
        list.refresh()
    }

Is this a correct way or I'm doing it wrong?


Solution

  • Yes this is the way you can change the listViewLayout of the RadListView component. I do see that you have a call to the .refresh() method, that is not necessary you simply have to set the new value to the listViewLayout property.

    You can change the in the official examples for RadListView here.