Handling Rotation - Xamarin (2022)

  • Article
  • 8 minutes to read

This topic describes how to handle device orientation changes in Xamarin.Android. It covers how to work with the Android resource system to automatically load resources for a particular device orientation as well as how to programmatically handle orientation changes.

Overview

Because mobile devices are easily rotated, built-in rotation is astandard feature in mobile OSes. Android provides a sophisticatedframework for dealing with rotation within applications, whether theuser interface is created declaratively in XML or programmatically incode. When automatically handling declarative layout changes on arotated device, an application can benefit from the tight integrationwith the Android resource system. For programmatic layout, changes mustbe handled manually. This allows finer control at runtime, but at theexpense of more work for the developer. An application can also chooseto opt out of the Activity restart and take manual control oforientation changes.

This guide examines the following orientation topics:

  • Declarative Layout Rotation – How to use the Androidresource system to build orientation-aware applications, includinghow to load both layouts and drawables for particular orientations.

  • Programmatic Layout Rotation – How to add controlsprogrammatically as well as how to handle orientation changesmanually.

Handling Rotation Declaratively with Layouts

By including files in folders that follow naming conventions, Androidautomatically loads the appropriate files when the orientation changes.This includes support for:

  • Layout Resources – Specifying which layout files areinflated for each orientation.

    (Video) Xamarin Android Tutorial 61 Handling Orientation Changes

  • Drawable Resources – Specifying which drawables are loadedfor each orientation.

Layout Resources

By default, Android XML (AXML) files included in theResources/layout folder are used for rendering views for anActivity. This folder's resources are used for both portrait andlandscape orientation if no additional layout resources are providedspecifically for landscape. Consider the project structure created bythe default project template:

This project creates a single Main.axml file in theResources/layout folder. When the Activity's OnCreate method iscalled, it inflates the view defined in Main.axml, which declares abutton as shown in the XML below:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"><Button android:id="@+id/myButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello"/></LinearLayout>

If the device is rotated to landscape orientation, the Activity'sOnCreate method is called again and the same Main.axml file isinflated, as shown in the screenshot below:

Orientation-Specific Layouts

In addition to the layout folder (which defaults to portrait and canalso be explicitly named layout-port by including a folder namedlayout-land), an application can define the views it needs when inlandscape without any code changes.

Suppose the Main.axml file contained the following XML:

(Video) Xamarin Forms - Rotation Animation

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:text="This is portrait" android:layout_height="wrap_content" android:layout_width="fill_parent" /></RelativeLayout>

If a folder named layout-land that contains an additional Main.axmlfile is added to the project, inflating the layout when in landscapewill now result in Android loading the newly added Main.axml. Considerthe landscape version of the Main.axml file that contains the followingcode (for simplicity, this XML is similar to the default portraitversion of the code, but uses a different string in the TextView):

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:text="This is landscape" android:layout_height="wrap_content" android:layout_width="fill_parent" /></RelativeLayout>

Running this code and rotating the device from portrait to landscapedemonstrates the new XML loading, as shown below:

Drawable Resources

During rotation, Android treats drawable resources similarly to layoutresources. In this case, the system gets the drawables from theResources/drawable and Resources/drawable-land folders,respectively.

For example, say the project includes an image named Monkey.png in theResources/drawable folder, where the drawable is referenced from anImageView in XML like this:

<ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/monkey" android:layout_centerVertical="true" android:layout_centerHorizontal="true" />

Let's further assume that a different version of Monkey.png is includedunder Resources/drawable-land. Just like with the layout files,when the device is rotated, the drawable changes for the givenorientation, as shown below:

Handling Rotation Programmatically

Sometimes we define layouts in code. This can happen for a variety ofreasons, including technical limitations, developer preference, etc.When we add controls programmatically, an application must manuallyaccount for device orientation, which is handled automatically when weuse XML resources.

(Video) Screen Orientation Android - Xamarin Forms

Adding Controls in Code

To add controls programmatically, an application needs to perform thefollowing steps:

  • Create a layout.
  • Set layout parameters.
  • Create controls.
  • Set control layout parameters.
  • Add controls to the layout.
  • Set the layout as the content view.

For example, consider a user interface consisting of a singleTextView control added to a RelativeLayout, as shown in thefollowing code.

protected override void OnCreate (Bundle bundle){ base.OnCreate (bundle); // create a layout var rl = new RelativeLayout (this); // set layout parameters var layoutParams = new RelativeLayout.LayoutParams (ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.FillParent); rl.LayoutParameters = layoutParams; // create TextView control var tv = new TextView (this); // set TextView's LayoutParameters tv.LayoutParameters = layoutParams; tv.Text = "Programmatic layout"; // add TextView to the layout rl.AddView (tv); // set the layout as the content view SetContentView (rl);}

This code creates an instance of a RelativeLayout class and sets itsLayoutParameters property. The LayoutParams class is Android's wayof encapsulating how controls are positioned in a reusable way. Once aninstance of a layout is created, controls can be created and added toit. Controls also have LayoutParameters, such as the TextView inthis example. After the TextView is created, adding it to theRelativeLayout and setting the RelativeLayout as the content viewresults in the application displaying the TextView as shown:

Detecting Orientation in Code

If an application tries to load a different user interface for eachorientation when OnCreate is called (this will happen each time adevice is rotated), it must detect the orientation, and then load thedesired user interface code. Android has a class called theWindowManager, which can be used to determine the current devicerotation via the WindowManager.DefaultDisplay.Rotation property, asshown below:

protected override void OnCreate (Bundle bundle){ base.OnCreate (bundle); // create a layout var rl = new RelativeLayout (this); // set layout parameters var layoutParams = new RelativeLayout.LayoutParams (ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.FillParent); rl.LayoutParameters = layoutParams; // get the initial orientation var surfaceOrientation = WindowManager.DefaultDisplay.Rotation; // create layout based upon orientation RelativeLayout.LayoutParams tvLayoutParams; if (surfaceOrientation == SurfaceOrientation.Rotation0 || surfaceOrientation == SurfaceOrientation.Rotation180) { tvLayoutParams = new RelativeLayout.LayoutParams (ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.WrapContent); } else { tvLayoutParams = new RelativeLayout.LayoutParams (ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.WrapContent); tvLayoutParams.LeftMargin = 100; tvLayoutParams.TopMargin = 100; } // create TextView control var tv = new TextView (this); tv.LayoutParameters = tvLayoutParams; tv.Text = "Programmatic layout"; // add TextView to the layout rl.AddView (tv); // set the layout as the content view SetContentView (rl);}

This code sets the TextView to be positioned 100 pixels from the topleft of the screen, automatically animating to the new layout, whenrotated to landscape, as shown here:

Preventing Activity Restart

In addition to handling everything in OnCreate, an application canalso prevent an Activity from being restarted when the orientationchanges by setting ConfigurationChanges in the ActivityAttribute asfollows:

(Video) Xamarin Forms Button Rotation Animation

[Activity (Label = "CodeLayoutActivity", ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]

Now when the device is rotated, the Activity is not restarted. In orderto manually handle the orientation change in this case, an Activity canoverride the OnConfigurationChanged method and determine theorientation from the Configuration object that is passed in, as inthe new implementation of the Activity below:

[Activity (Label = "CodeLayoutActivity", ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]public class CodeLayoutActivity : Activity{ TextView _tv; RelativeLayout.LayoutParams _layoutParamsPortrait; RelativeLayout.LayoutParams _layoutParamsLandscape; protected override void OnCreate (Bundle bundle) { // create a layout // set layout parameters // get the initial orientation // create portrait and landscape layout for the TextView _layoutParamsPortrait = new RelativeLayout.LayoutParams (ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.WrapContent); _layoutParamsLandscape = new RelativeLayout.LayoutParams (ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.WrapContent); _layoutParamsLandscape.LeftMargin = 100; _layoutParamsLandscape.TopMargin = 100; _tv = new TextView (this); if (surfaceOrientation == SurfaceOrientation.Rotation0 || surfaceOrientation == SurfaceOrientation.Rotation180) { _tv.LayoutParameters = _layoutParamsPortrait; } else { _tv.LayoutParameters = _layoutParamsLandscape; } _tv.Text = "Programmatic layout"; rl.AddView (_tv); SetContentView (rl); } public override void OnConfigurationChanged (Android.Content.Res.Configuration newConfig) { base.OnConfigurationChanged (newConfig); if (newConfig.Orientation == Android.Content.Res.Orientation.Portrait) { _tv.LayoutParameters = _layoutParamsPortrait; _tv.Text = "Changed to portrait"; } else if (newConfig.Orientation == Android.Content.Res.Orientation.Landscape) { _tv.LayoutParameters = _layoutParamsLandscape; _tv.Text = "Changed to landscape"; } }}

Here the TextView's layout parameters are initialized for bothlandscape and portrait. Class variables hold the parameters, along withthe TextView itself, since the Activity will not be re-created whenorientation changes. The code still uses the surfaceOrientartion inOnCreate to set the initial layout for the TextView. After that,OnConfigurationChanged handles all subsequent layout changes.

When we run the application, Android loads the user interface changesas device rotation occurs, and does not restart the Activity.

Preventing Activity Restart for Declarative Layouts

Activity restarts caused by device rotation can also be prevented if wedefine the layout in XML. For example, we can use this approach if wewant to prevent an Activity restart (for performance reasons, perhaps)and we don't need to load new resources for different orientations.

To do this, we follow the same procedure that we use with aprogrammatic layout. Simply set ConfigurationChanges in theActivityAttribute, as we did in the CodeLayoutActivity earlier. Anycode that does need to run for the orientation change can again beimplemented in the OnConfigurationChanged method.

Maintaining State During Orientation Changes

Whether handling rotation declaratively or programmatically, allAndroid applications should implement the same techniques for managingstate when device orientation changes. Managing state is importantbecause the system restarts a running Activity when an Android deviceis rotated. Android does this to make it easy to load alternateresources, such as layouts and drawables that are designed specificallyfor a particular orientation. When it restarts, the Activity loses anytransient state it may have stored in local class variables. Therefore,if an Activity is state reliant, it must persist its state at theapplication level. An application needs to handle saving and restoringany application state that it wants to preserve across orientationchanges.

For more information on persisting state in Android, refer to theActivity Lifecycleguide.

Summary

This article covered how to use Android's built-in capabilities to workwith rotation. First, it explained how to use the Android resourcesystem to create orientation aware applications. Then it presented howto add controls in code as well as how to handle orientation changesmanually.

(Video) Xamarin.Forms: Orientation Change - Kym Phillpotts - Xamarin University Lightning Lecture

This article explains how to use matrix transforms to implement touch dragging, pinching, and rotation, and demonstrates this with sample code.

As you experiment with this program, take note that you can only drag the bitmap when your finger touches an area where the bitmap is displayed.. When scaling a bitmap, it makes most sense for the two fingers to remain in the same positions relative to the bitmap, and for the bitmap to be scaled accordingly.. In the Bitmap Scaling page code below, the finger that has not changed position is called the pivot point because the transform is relative to that point.. As you experiment with this page, you'll notice that you can drag the bitmap with one or two fingers, or scale it with two fingers.. If multiple fingers touch the bitmap, then the touchIds collection contains a touch ID for each finger.. However, it's possible to implement scaling with a single finger by having the finger move the corners of a bitmap.. For the Pressed action type, the handler checks that no other finger is touching the screen, and that the finger is within the bounds of the bitmap.

In a Xamarin.Forms application, XAML is mostly used to define the visual contents of a page and works together with a code-behind file.

App.xaml , the XAML file; and App.xaml.cs , a C# code-behind file associated with the XAML file.. Most other classes with XAML files contribute to a class that derives from ContentPage ; those files use XAML to define the visual contents of an entire page.. MainPage.xaml , the XAML file; and MainPage.xaml.cs , the C# code-behind file.. This means that this XAML file defines a new class named MainPage in the XamlSamples namespace that derives from ContentPage —the tag in which the x:Class attribute appears.. This is the only new class defined in the XAML file.. LoadFromXaml initializes all the objects defined in the XAML file, connects them all together in parent-child relationships, attaches event handlers defined in code to events set in the XAML file, and sets the resultant tree of objects as the content of the page.. At this time, the relationship between classes, properties, and XML should be evident: A Xamarin.Forms class (such as ContentPage or Label ) appears in the XAML file as an XML element.. Properties of that class—including Title on ContentPage and seven properties of Label —usually appear as XML attributes.. Back in the XAML file, the Slider and Button tags need to include attributes for the ValueChanged and Clicked events that reference these handlers:

Activities are a fundamental building block of Android applications and they can exist in a number of different states. The activity lifecycle begins with instantiation and ends with destruction, and includes many states in between. When an activity changes state, the appropriate lifecycle event method is called, notifying the activity of the impending state change and allowing it to execute code to adapt to that change. This article examines the lifecycle of activities and explains the responsibility that an activity has during each of these state changes to be part of a well-behaved, reliable application.

The activity lifecycle is implemented as a collection of methods the OS. calls throughout the lifecycle of an activity.. Activity States Lifecycle Methods Retaining the State of an Application. The following code illustrates how to. retrieve values from the bundle:. There will be no lifecycle methods called after the Activity has been destroyed.. If the user. were then to restore the application by using the task manager or a. similar application, Android will call the OnRestart method of the. activity.. An Activity provides methods to help with saving and retrieving the instance state in the Bundle:. In addition to persisting data in the bundle, Android also supports. saving data by overriding. and returning an instance of a Java.Lang.Object that contains the. data to persist.

The Xamarin.Forms Slider is a horizontal bar that can be manipulated by the user to select a double value from a continuous range. This article explains how to use the Slider class to select a value from a range of continuous values.

If the Minimum property is set to a value greater than the Value property, the Slider sets the Value property to Minimum .. Slider defines a ValueChanged event that is fired when the Value changes, either through user manipulation of the Slider or when the program sets the Value property directly.. The first page uses only C# code, the second uses XAML with an event handler in code, and the third is able to avoid the event handler by using data binding in the XAML file.. The Basic Slider Code page in the SliderDemos sample shows show to create a Slider and two Label objects in code:. The ValueChanged handler of the Slider uses the Value property of the slider object to set the Rotation property of the first Label and uses the String.Format method with the NewValue property of the event arguments to set the Text property of the second Label .. The second Label displays the text "(uninitialized)" until the Slider is manipulated, which causes the first ValueChanged event to be fired.. The Basic Slider Bindings page functions a little differently from the two previous pages: When the page first appears, the second Label displays the text string with the value.. The value of the Minimum property must always be less than the value of the Maximum property.. When Minimum is set to 10, Value is also set to 10, and the ValueChanged event is fired.. If you set the Slider to have a Minimum of 0 and a Maximum of 5000, then as the Slider is manipulated, the Value property has values of 0, 5, 10, 15, and so forth.. The StepFrequency property of the UWP Slider is set to the difference of the Maximum and Minimum properties divided by 10, but not greater than 1.. This allows all the elements in the XAML file to bind to properties in the ViewModel:

Games and 3D applications rely on DirectX and OpenGL to provide APIs that allow them to interact with the amazing graphics processors available at our disposal. Over the years, these APIs have matured, becoming much more accessible and easier to get started with. In this article, Toptal engineer Timofey Lonchakov...

In this introduction to OpenGL, I will explain how to write a very simple application to render 3D text models.. The goal of this simple application is to generate 3D models, save them to a file with a simple format, and to open and render them on screen.. Before getting started, we will need to prepare our development environment with some useful tools for this project.. This widget is used to render the 3D scene.. mainwindow.h/cpp Contains implementation of the main application widget.. model3d.h/cpp Contains structures which store 3D model objects and allow operations to work on them (save, load etc.. For OpenGL based 3D rendering, Qt provides a widget called QOpenGLWidget.. The third line makes the program render triangles regardless of which direction their normals point to.. For improved performance, we used Vertex Buffer Object (VBO) in our prototype application.. To compute this transformation matrix, we compute a few separate matrices: screen scale, translate scene, scale, rotate, and center.. However, the purpose of this article is to give you a peek into this realm, and show how easily you can get started with OpenGL to build 3D applications.

Want to harness the potential of an automation tool? Check out the Microsoft Power Automate use cases along with benefits to understand its impact across different industries.

Part of Microsoft’s Power Platform suite, this cloud-based tool allows automation of workflows and processes for businesses.. Previously known as Microsoft Flow, it is primarily a business process automation (BPA) software with the option to include attended and unattended bots.. Creation of workflows Task automation based on recurring, frequent and routine status Automation of legacy business processes Logic design for Power Apps. Cloud flows Business process flows Desktop flows. For instance, if you want a flow to be created every time a user adds a new item to your SharePoint list, you can create an automated flow with the “when an item is added” trigger and pair it with the corresponding list.. Business Process Flows: Ideal for streamlining tasks and processes, it helps assure that everyone carries out specific tasks in a similar way with consistent data entry.. Desktop Flows: Typically used for automating tasks on the desktop and web through Power Automate Desktop.. Automation of repetitive tasks with this tool means almost 0 errors in your business processes.. Automation of patient registration & discharge Helpdesk process automation Moving test results to EHR systems Automation of staff onboarding and shift rotation Billing & claims automation Document approval workflow. Inventory & freight management automation Automation of real-time information flow across systems like POS & inventory control HR processes automation – onboarding & offboarding, payroll, and reporting Automation of processes like sales analytics, return orders, new product launch and more. As a powerful tool that steers your business towards success, Microsoft Power Automate is the ideal solution to streamline critical processes, intelligently!

This article shows how to implement an ASP.NET Core Razor page to authenticate against Azure B2C and use Web APIs from a second ASP.NET Core application which are also protected using Azure B2C App…

The APIs are implemented using ASP.NET Core and this uses Azure B2C to validate and authorize the access tokens.. The Admin API uses claims specific to the Azure AD identity to authorize only Azure AD internal users.. Three Azure App registrations were created in Azure B2C to support the setup above.. The UI Azure App registration is setup to use an Azure B2C user flow and will have access to both APIs.. A single tenant Azure App registration needs to be created in the Azure AD for the internal or admin users.. A custom identity provider needs to be created to access the single tenant Azure AD for the admin identity authentication.. The idp claim is required and idp_access_token claim if you require user data from the Azure AD identity.. Add the required claims when creating the user flow.. The claims can be added when creating the user flow in the User attributes and token claims section.. The idp and the idp_access_token are added for the Azure AD sign-in and this can be validated when using the admin API.. If you require only a subset of identities from the Azure AD tenant, an enterprise app can be used to define the users which can use the Azure AD App registration.

At SQUALAS, we provide high-value E-Commerce, Web, and Mobile Development Services.

2+ Years of work experience.. Good working knowledge of SQL 2008.. (Good to have). IT Project Manager Send Profile To : contact@squalas.com. Good communication Skills are required.. 3+ years of experience as Business Analyst related to Digital Engineering Experience managing a team of resources with Strong problem solving & analytical skills Excellent Written and Oral Communication Skills, Presentation Skills Experience working with Onshore and Offshore Teams and Experience handling Cross-Functional Projects, Resources and Clients Have in either of these domains: US focused Retail, Pharma, eCommerce, HealthCare, EduTech, etc You have a track record of delivering impactful software, ideally on a collaborative software delivery team.. 5+ year experience with C++, Experience in C++ development and maintenance Excellent analytical and debugging skills Experience with tools like GDB JIRA GIT GCC toolchain Strong object oriented development skills Use of design patterns and well versed with UML design notations Unit test frameworks like Gmock and Gtest Experience with Agile way of working Good communication skills Development experience in windows and Linux environments Should be able to understand the UI wireframes and use standard practices to develop UI. Minimum 3 years of proven experience as a Full Stack Developer (Next.Js & MERN) Experience developing Web, desktop and mobile applications Experience of multiple languages, frameworks and libraries (e.g. HTML/ CSS, JavaScript, XML, jQuery, React.Js, Next.Js) Experience working with MongoDB along with AWS Excellent communication and teamwork skills Great attention to detail Organizational skills An analytical mind Degree in Computer Science, Statistics or relevant field Responsibilities Work with development teams and product managers to ideate software solutions Design client-side and server-side architecture Able to work with Cloud Hosting Services such as AWS Build the front-end of applications through appealing visual design Develop and manage well-functioning/structured backend code and applications Write effective APIs Test software to ensure responsiveness and efficiency Troubleshoot, debug and upgrade software Create security and data protection settings Build features and applications with a mobile responsive design (Progressive Web Application) Write technical documentation Extensive knowledge of working with data to improve software Co-ordinate with fellow team members and do the proper code review and train Interns

Videos

1. Xamarin.forms Basic Controls and event handling
(John Okoroafor)
2. Blazor on Xamarin Android. Rotating the screen.
(jwspuij)
3. Prevent Orientation change in Xamarin Android Application - C#
(Solutions Cloud)
4. Xamarin.Forms 3.0 - FlexLayout
(John Okoroafor)
5. Demo of Xamarin iOS plugin for works with device orientation on runtime.
(Yauheni Pakala)
6. Using class Matrix for rotating and scaling 2d Clock C# Xamarin
(programmer)

You might also like

Latest Posts

Article information

Author: Delena Feil

Last Updated: 09/12/2022

Views: 5736

Rating: 4.4 / 5 (45 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.