In today world, media contents (like apps, websites, etc.) must have a responsive layout that can be adapted and adjusted quickly to suit to the orientation and the size of the platform’s screen on which they are runned.
It is very common to see this feature in websites, as their layout change on mobile, desktop and even on tablet screen. Native apps created with platform manufacturer’s IDE can have also these feature enabled.
But on cross platform dev tools like Delphi FMX, it may be kind tricky to implement this feature.
Delphi FMX provides a platform service to detect screen orientation on the current platform. We will show how to use it correctly to create responsive apps from a single code base in this tutorial.
First, add the FMX.Platform to the uses clause.
Now, you can use the screen orientation’s service to create a condition to hide/show and change dimensions of some controls and layouts when the screen orientation is portrait (and inverted portrait) or landscape (and inverted landscape).
Then, you have to write a call to this routine inside an event handler like the Form’s OnResize or OnActivate events (or you can write the whole routine inside the event’s procedure).
- The FormResize event handler is executed when the form get resized (by the mouse, the user’s control or by the OS) even if it didn’t get focus. It is very suitable to our implentation : When the form get resized, it will detect the screen orientation and the form’s contents will be adjusted.
- Or, the FormActivate event handler is executed when the form recieve focus, so it is less suitable to our implentation. When the form recieve focus, it will detect the screen orientation and the form’s contents will be adjusted.
procedure TMainForm.FormResize(Sender: TObject); var Screen : IFMXScreenService; begin if TPlatformServices.Current.SupportsPlatformService(IFMXScreenService, IInterface(Screen)) then begin if (Screen.GetScreenOrientation = TScreenOrientation.Portrait) or (Screen.GetScreenOrientation = TScreenOrientation.InvertedPortrait) then begin //Vertical LayoutHeaderBar.Visible := False; LayoutMenuHeader.Visible := True; LayoutStartup.Margins.Top := 120; LayoutStartup.Margins.Left := 10; LayoutStartup.Margins.Right := 10; LayoutStartup.Margins.Bottom := 150; end else if (Screen.GetScreenOrientation = TScreenOrientation.Landscape) or (Screen.GetScreenOrientation = TScreenOrientation.InvertedLandscape) then begin //Horizontal LayoutHeaderBar.Visible := True; LayoutMenuHeader.Visible := False; LayoutStartup.Margins.Top := 120; LayoutStartup.Margins.Left := 150; LayoutStartup.Margins.Right := 150; LayoutStartup.Margins.Bottom := 60; end end; end;
As you can see, we implemented a routine to hide/show some layouts and change the dimensions of some controls according to the current platform screen’s orientation.