Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to share UI Code across Mobile platforms with Xamarin.Forms

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

Today, I will talk to you about how to share UI code across mobile platforms with the help of Xamarin.Forms. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

With Xamarin, you can use C # to build beautiful native mobile applications and share most of your code between platforms. Traditionally, you have to design a separate UI for each target platform. However, with Xamarin.Forms, you can build a UI that is natively rendered on all platforms.

Xamarin.Forms is a cross-platform UI abstraction layer. You can use it to share UI and back-end code between platforms while still providing a full native UI experience. Because they are native, your controls and widgets will have the appearance of each target platform.

Xamarin.Forms is fully compatible with the Model-View-ViewModel (MVVM) design pattern, so you can bind page elements to properties and commands in the view model class.

If you prefer to design your page declaratively, you can use the markup language XAML,XAML to have functions such as resource dictionaries, dynamic resources, data binding, commands, triggers, and behaviors.

Xamarin.Forms has a small, easy to use API. If you need more in-depth access to the platform's native UI, you can create custom views and platform-specific renderers. Complicated as it sounds, it's really just a way to access native UI, and the Xamarin Web site has plenty of examples to help you with this task.

You can get started with any of the ready-made pages, layouts, and views that come with Xamarin.Forms. As your application refines and you discover new use cases and design opportunities, you may immediately need to rely on Xamarin.Forms support for XAML, MVVM, custom platform-specific renderers, and various other features (such as animation and data templates).

I'll use specific examples to outline Xamarin functionality, demonstrate how to share most of the UI code between different target platforms, and how to merge platform-specific code if necessary.

Start using

First, open the NuGet package manager in Visual Studio or Xamarin Studio and check to see if Xamarin.Forms is a new version. Because only opening the Xamarin.Forms solution in any IDE won't tell you about the new version, checking that the updated NuGet package is the only way to make sure you get the latest enhancements.

After creating a Xamarin.Forms solution to ensure that you have the latest version of Xamarin.Forms, create a blank application (Xamarin.Forms Portable) solution.

Your solution has three platform-specific projects and a portable class library (PCL). Create your page in PCL. First create a basic login page.

Use the C # creation page to add a class to the PCL project. Then add controls (called "views" in Xamarin), as shown in figure 1.

Figure 1 add View (Control)

Public class LogInPage: ContentPage {public LogInPage () {Entry userEntry = new Entry {Placeholder = "Username"}; Entry passEntry = new Entry {Placeholder = "Password", IsPassword = true}; Button submit = new Button {}; Content = new StackLayout {Padding = 20, VerticalOptions = LayoutOptions.Center, Children = {userEntry, passEntry, submit}};}}

To display the page when the application starts, open the MyApp class and assign one of the instances to the MainPage property:

Public class MyApp: Application {public MyApp () {MainPage = new LogInPage ();}}

This is a good time to discuss application classes. Starting with v1.3.0, all Xamarin.Forms applications will include this class. It is the entry point for Xamarin.Forms applications, in addition to providing lifecycle events and a permanent data store (attribute dictionary) for all serializable data. If you need to access an instance of this class from anywhere in the application, you can use the static Application.Current property.

In the previous example, I removed the default code inside the application class and replaced it with a single line of code so that LogInPage shows when you are running the application. It shows when the application runs because this code assigns the page (LogInPage) to the MainPage property of the application class. You must set it in the constructor of the application class.

You can also override three methods in this class:

The OnStart method, called when the application is started for the first time.

The OnSleep method, which is called when the application is about to enter the background state.

The OnResume method is called when the application is returned from the background state.

In general, pages are not very interesting until you connect them to some form of data or behavior, so I'll show you how to do this.

Bind a page to data if you use the MVVM design pattern, you can create a class (shown in figure 2) that implements the INotifyPropertyChanged interface.

Figure 2 implements the INotifyPropertyChanged interface

Public class LoginViewModel: INotifyPropertyChanged {private string usrnmTxt; private string passWrd; public string UsernameText {get {return usrnmTxt;} set {if (usrnmTxt = = value) return; usrnmTxt = value; OnPropertyChanged ("UsernameText");}} public string PassWordText {get {return passWrd;} set {if (passWrd = = value) return; passWrd = value; OnPropertyChanged ("PassWrd") } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged (string propertyName) {if (PropertyChanged! = null) {PropertyChanged (this, new PropertyChangedEventArgs (propertyName));}

You can bind the view of the login page to the properties of the class (as shown in figure 3).

Figure 3 binds the view to the class properties

Public LogInPage () {Entry userEntry = new Entry {Placeholder = "Username"}; userEntry.SetBinding (Entry.TextProperty, "UsernameText"); Entry passEntry = new Entry {Placeholder = "Password", IsPassword = true}; passEntry.SetBinding (Entry.TextProperty, "PasswordText"); Button submit = new Button {Text = "Submit"}; Content = new StackLayout {Padding = 20, VerticalOptions = LayoutOptions.Center, Children = {userEntry, passEntry, submit}}; BindingContext = new LoginViewModel () }

To read more about how to bind to data in a Xamarin.Forms application, see "from data binding to MVVM" on the Xamarin site bit.ly/1uMoIUX.

Using XAML to create pages for smaller applications, using C # to create UI is a perfectly reasonable approach. However, as the application size grows, you may find yourself typing a lot of duplicate code. You can avoid this problem by using XAML, not through C # code.

Add a form XAML page item to your PCL project. Then add the tag to the page, as shown in figure 4.

Figure 4 add a tag to the form XAML page

If you have written a Windows Presentation Foundation (WPF) application, you will be familiar with the XAML in figure 4. However, these tags are different because they refer to the Xamarin.Forms type. In addition, the root element references a subclass of the Xamarin.Forms.Element class. All XAML files in the Xamarin.Forms application must do this.

To learn more about creating pages in Xamarin.Forms applications using XAML, see "XAML for Xamarin.Forms" on the Xamarin website bit.ly/1xAKvRN.

Design specific platform

Compared with other native mobile platforms, Xamarin.Forms has relatively few API. This makes it easier for you to design the page, but sometimes Xamarin.Forms does not render the view on one or more platform goals the way you want.

If you encounter this obstacle, you only need to create a custom view, which is just a subclass of any view that can be used with Xamarin.Forms.

To make the view appear on the page, expand the view renderer. In more advanced cases, you can even create a custom renderer from scratch. The custom renderer code is platform specific, so you cannot share this code. But this method is worth the price because it can introduce native features and application availability.

To create a custom view, first, create a subclass of any view provided in Xamarin.Forms. Here is the code for two custom views:

Public class MyEntry: Entry {} public class RoundedBoxView: BoxView {}

Extend the existing renderer figure 5 extends the renderer that renders the item view of the iOS platform. You should put this class in your iOS platform project. This renderer sets the color and style of the underlying native text field.

Figure 5 extending the existing renderer

[assembly: ExportRenderer (typeof (MyEntry), typeof (MyEntryRenderer))] namespace CustomRenderer.iOS {public class MyEntryRenderer: EntryRenderer {protected override void OnElementChanged (ElementChangedEventArgs e) {base.OnElementChanged (e); if (e.OldElement = = null) {var nativeTextField = (UITextField) Control; nativeTextField.BackgroundColor = UIColor.Gray; nativeTextField.BorderStyle = UITextBorderStyle.Line;}

You can perform almost anything on the renderer because you are referencing the native API. If you want to see an example that contains this code snippet, see "Xamarin.Forms Custom Renderer" on bit.ly/1xTIjmR.

Creating a renderer from scratch creates a completely new renderer that does not extend any other renderers. Creating a renderer requires more work, but it is useful to do any of the following:

Replace the renderer of the view.

Add a new view type to your solution.

Add native controls or native pages to your solution.

For example, if you want to add a native UIView control to a page applied by the iOS version, you should add a custom renderer to your iOS project, as shown in figure 6.

Figure 6 adding a native UIView control to an iOS application with a custom renderer

[assembly: ExportRendererAttribute (typeof (RoundedBoxView), typeof (RoundedBoxViewRenderer))] namespace RBVRenderer.iOS {public class RoundedBoxViewRenderer: ViewRenderer {protected override void OnElementChanged (ElementChangedEventArgs e) {base.OnElementChanged (e); var rbvOld = e.OldElement; if (rbvOld! = null) {/ / Unhook any events from e.OldElement here. } var rbv = e.NewElement; if (rbv! = null) {var shadowView = new UIView (); / / Set properties on the UIView here. SetNativeControl (shadowView); / / Hook up any events from e.NewElement here. }

The common pattern shown in this renderer ensures that you can use this pattern in a virtualized layout, such as a list view, which I will discuss later.

If you want to see an example that contains this code snippet, see bit.ly/xf-customrenderer.

Add properties to a custom view you can add properties to a custom view, but make sure they are bindable so that you can bind them to properties in the view model or other types of data. Here are the properties that can be bound in an RoundedBoxView custom view:

Public class RoundedBoxView: BoxView {public static readonly BindableProperty CornerRadiusProperty = BindableProperty.Create (p = > p.CornerRadius, 0); public double CornerRadius {get {return (double) base.GetValue (CornerRadiusProperty);} set {base.SetValue (CornerRadiusProperty, value);}

To connect a new property to your renderer, override the renderer's OnElementPropertyChanged method and add code that runs when the property changes:

Protected override void OnElementPropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e) {base.OnElementPropertyChanged (sender, e); if (e.PropertyName = = RoundedBoxView.CornerRadiusProperty.PropertyName) childView.Layer.CornerRadius = (float) this.Element.CornerRadius;}

To learn more about creating custom views and custom renderers, see "customizing controls for each platform" on bit.ly/11pSFhL.

Pages, layouts, and views: the building blocks of Xamarin.Forms

I've shown a few elements, but there's more. This is a good time to introduce these elements.

Xamarin.Forms applications include pages, layouts, and views. A page contains one or more layouts, and a layout contains one or more views. Use the term view in Xamarin to describe your habit of calling controls. Overall, the Xamarin.Forms framework consists of five page types, seven layout types, and 24 view types. You can get more information through xamarin.com/forms. Later, I'll introduce some important page types, but first I'll take a moment to review some layouts that you can use in your application. Xamarin.Forms consists of four main layouts:

StackLayout:StackLayout locates child elements in a single vertical or horizontal row. You can nest StackLayouts to create complex visual hierarchies. You can control how views are arranged in StackLayout by using the VerticalOptions and Horizontal ­Options properties of each child view.

Grid: the grid arranges views into rows and columns. This layout is similar to the layout obtained using WPF and Silverlight, but you cannot add gaps between rows and columns. This is done by using the RowSpacing and ColumnSpacing properties of the grid.

RelativeLayout: RelativeLayout can position the view by using constraints relative to other views.

AbsoluteLayout:AbsoluteLayout can position child views in two ways: absolute positioning or proportional positioning relative to the parent. This helps to create a split and overlay hierarchy. Figure 7 shows an example.

Figure 7 using AbsoluteLayout

Void AbsoluteLayoutView () {var layout = new AbsoluteLayout (); var leftHalfOfLayoutChild = new BoxView {Color = Color.Red}; var centerAutomaticallySizedChild = new BoxView {Color = Color.Green}; var absolutelyPositionedChild = new BoxView {Color = Color.Blue}; layout.Children.Add (leftHalfOfLayoutChild, new Rectangle (0,0,0.5,1), AbsoluteLayoutFlags.All); layout.Children.Add (centerAutomaticallySizedChild, new Rectangle (0.5,0.5,0.5,AbsoluteLayout.AutoSize), AbsoluteLayoutFlags.PositionProportional) Layout.Children.Add (absolutelyPositionedChild, new Rectangle (10,20,30,40);}

Notice that all layouts provide you with a property named Children. This property can be used to access other members. For example, you can use the Children property of a grid layout to add and remove rows and columns, and to specify row and column spacing.

Display data in a scrolling list

You can display data in a scrolling list by using a list view form named ListView. This view performs well because the renderer for each cell in the list is virtualized. Because each cell is virtualized, it is important to properly handle the OnElementChanged event of any custom renderer created for the cell or list by using a pattern similar to the previous one.

First, define a cell, as shown in figure 8. All ListView data templates must use a cell as the root element.

Figure 8 defines the ListView cell

Public class MyCell: ViewCell {public MyCell () {var nameLabel = new Label (); nameLabel.SetBinding (Label.TextProperty, "Name"); var descLabel = new Label (); descLabel.SetBinding (Label.TextProperty, "Description"); View = new StackLayout {VerticalOptions = LayoutOptions.Center, Children = {nameLabel, descLabel}};}}

Next, define the data source and set the ItemTemplate property of ListView on the new data template. The data template is based on the MyCell class you created earlier:

Var items = new [] {new {Name = "Flower", Description = "A lovely pot of flowers."}, new {Name = "Tuna", Description = "A can of tuna!"}, / /. Add more items}; var listView = new ListView {ItemsSource = items, ItemTemplate = new DataTemplate (typeof (MyCell))}

You can do this in XAML with the following tags:

Navigate between pages

Most applications contain multiple pages, so you need to enable users to navigate from one page to another. The following pages have built-in support for page navigation and support for full-screen mode page presentations:

TabbedPage

MasterDetailPage

NavigationPage

CarouselPage

You can add pages as children to any of these four pages and get navigation for free.

TabbedPage TabbedPage displays an array of tabs across the top of the screen. Assuming that the PCL project contains pages named LogInPage, DirectoryPage, and AboutPage, you can add all of these pages to TabbedPage using the following code:

Var tabbedPage = new TabbedPage {Children = {new LoginPage {Title = "Login", Icon = "login.png"}, new DirectoryPage {Title = "Directory", Icon = "directory.png"}, new AboutPage {Title = "About", Icon = "about.png"}

In this case, it is important to set the title and icon properties of each page, which allows some content to be displayed on the page tab. Not all platforms render icons. This depends on the tab design of the platform.

If you open this page on a mobile device, the first tab appears selected. However, you can change this state by setting the CurrentPage property of the TabbedPage page.

NavigationPageNavigationPage manages navigation and UX for a large number of pages. This page provides you with the most common types of mobile application navigation modes. Here's how to add your page to it:

Var loginPage = new LoginPage (); var navigationPage = new NavigationPage (loginPage); loginPage.LoginSuccessful + = async (o, e) = > await navigationPage.PushAsync (new DirectoryPage ())

Note that the PushAsync method is used to navigate the user to a specific page (in this case, DirectoryPage). In NavigationPage, you can "push" a page to the stack and then "pop" it as the user navigates back to the previous page.

NavigationPage's PushAsync and PopAsync methods are asynchronous, so your code should wait for them instead of pushing or popping up any new pages while running the task. When the push or pop-up animation is complete, return to the task for each method.

For convenience, all Xamarin.Forms views, layouts, and pages contain navigation properties. This property is a proxy interface that contains the PushAsync and PopAsync methods of the NavigationPage instance. This property can be used to navigate to the page rather than directly calling the PushAsync and PopAsync methods of the NavigationPage instance. NavigationProperty can also be used to get the PushModalAsync and PopModalAsync methods. This helps to replace the contents of the entire screen with the new mode page. It is not necessary to have a NavigationPage in the view's parent stack to use the view's navigation properties, but modeless PushAsync/PopAsync operations may fail.

Comments about design patterns typically add NavigationPages as a child to TabbedPages and TabbedPages as a child to MasterDetailPages. Some types of patterns can result in unexpected UX. For example, most platforms recommend that you do not add TabbedPage as a child of NavigationPage.

Animate the view on the page

There are two ways to animate the views on the page to create a more attractive user experience. Choose the built-in animation that comes with Xamarin.Forms, or build it yourself by using the animated API.

For example, you can create a fade effect by invoking the FadeTo animation of a view. FadeTo animation is built into the view, so it is easy to use:

Async Task SpinAndFadeView (View view) {await view.FadeTo (20, length: 200, easing: Easing.CubicInOut);}

You can link a series of animations together by using the await keyword. After the previous one is completed, each animation is executed. For example, you can rotate a view before diluting it to focus:

Async Task SpinAndFadeView (View view) {await view.RotateTo (180); await view.FadeTo (20, length: 200, easing: Easing.CubicInOut);}

If you have problems achieving the desired effect, you can use a full animated API. In the following code, fade half by rotating the view:

Void SpinAndFadeView (View view) {var animation = new Animation (); animation.Add (0,1, new Animation (d = > view.Rotation = d, 0180, Easing.CubicInOut)); animation.Add (0.5,1, new Animation (d = > view.Opacity = d, 1,0, Easing.Linear)); animation.Commit (view, "FadeAndRotate", length: 250);}

This example combines each animation into a single animation instance, and then uses the Commit method to run the entire animation sequence. Because this animation cannot be limited to a specific view, you can apply this animation to any view.

Xamarin.Forms is an exciting new way to build native mobile applications across platforms. Use it to build UI native rendering across iOS, Android, and Windows Phone. You can share almost all code between platforms.

Xamarin Inc. Building Xamarin and Xamarin.Forms allows C # developers to jump to mobile development almost quickly. If you are already developing for the Windows runtime, WPF, or Silverlight, you will find that Xamarin.Forms is a convenient bridge in the field of cross-platform native mobile development. You can install Xamarin immediately and start using clips immediately to build beautiful native applications that run on iOS, Android, and Windows Phone devices.

After reading the above, do you have any further understanding of how to share UI code across mobile platforms with Xamarin.Forms? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report