Search code examples
nativescript

position element at center of absolute layout in nativescript


I have a list of objects coming from api which I am showing in a ListView. For each item in the list, i am rendering an absolute layout. If the item has photo I show it full stretched so that it appear as a background image for that item in the list. Then I am rendering button with item name which i want to render right at the center of the image. I went through the docs but could not find a way to do it.

<ListView [items]="List">
  <StackLayout>
    <template let-item="item">
      <AbsoluteLayout  class="list-item">
        <Image src="{{item.photo}}" *ngIf="item.photo" stretch="fill">  </Image>
        <Button [text]="item.name" (tap)="onItemTap(item)"></Button>
      </AbsoluteLayout>
    </template>
  </StackLayout>    
</ListView>

Solution

  • Place a GridLayout inside the AbsoluteLayout, then place the Button which should be centered inside the GridLayout:

    <AbsoluteLayout  class="list-item">
        <Image src="{{item.photo}}" *ngIf="item.photo" stretch="fill">  </Image>
        <GridLayout background="transparent">
            <Button [text]="item.name" (tap)="onItemTap(item)"></Button>
        </GridLayout>
    </AbsoluteLayout>