Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Fill Empty Space With UI Elements Using The NativeScript GridLayout

TwitterFacebookRedditLinkedInHacker News

So recently I found myself needing to create a screen in a NativeScript Android and iOS app that had a ListView that sat below, or above, a Label UI element. The problem I faced was that there were issues with element sizing. On my first attempt I ended up with a Label and ListView that only took up a small portion of the screen, when I wanted the ListView to take up all remaining space. This is where the GridLayout comes in with its ability to have custom row and column sizing.

Using a GridLayout you can specify how rows and columns are fit around the screen.

Before going further, I wanted to say that I got inspiration for this article from Jen Looper’s article Demystifying NativeScript Layouts. Her article alone wasn’t enough to make me understand which is why I felt mine would be necessary.

I wanted to have a block of text, or in this case a Label to appear above a ListView. The ListView should fill any remaining space.

This is made possible by defining an automatic height to the first UI element and a wildcard fill height to the second. Both UI elements have a wildcard fill width.

So how do we do this? Let’s look at the following XML UI:

<Page loaded="pageLoaded">
    <Page.actionBar>
        <ActionBar title="Tasks">
            <ActionBar.actionItems>
                <ActionItem text="New" ios.position="right" />
            </ActionBar.actionItems>
        </ActionBar>
    </Page.actionBar>
    <GridLayout columns="*" rows="auto, *">
        <Label text="{{ project.name || 'project name' }}" row="0" col="0" class="projectTitle" />
        <ListView items="{{ tasks }}" row="1" col="0">
            <ListView.itemTemplate>
                <StackLayout>
                    <Label text="{{ name || 'test name' }}" />
                </StackLayout>
            </ListView.itemTemplate>
        </ListView>
    </GridLayout>
</Page>

Notice the use of columns and rows in the GridLayout tag.

Per Jen Looper’s explanation:

  • auto – the row or column takes on the dimensions of its child
  • pixel – a numeric value specifies the size of the cell in device independent pixels
  • star – value specifies the relative value against other stars

The star will allow us to fill empty space.

I tried this with a variety of columns and rows and it seemed to work out fine. Maybe this short little blurb on the subject will help someone else facing a similar dilemma.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.