神刀安全网

Building Polished Mobile Apps with Telerik UI for NativeScript

Telerik UI for NativeScript is a set of Telerik-built premium components for building high-quality NativeScript apps. Now that UI for NativeScript has officially been released , let’s look at some of the cool things you can build with the component suite, starting with a quick look at how to get up and running.

Note: The hands-on examples presented in this article assume you have the NativeScript command-line utility installed on your development machine. If you don’t have the CLI installed and want to follow along, you’ll need to go through the CLI’s installation instructions first. If you’re new to NativeScript, you may also want to go through the official NativeScript Getting Started Guide before playing with UI for NativeScript.

Table of Contents

  • Getting up and running
    • Basic side drawer navigation
    • Implementing an options menu
    • Sharing a drawer across pages
    • Implementing pull to refresh
    • Adding swipe to execute actions

Getting up and running

The various UI for NativeScript components are packaged into a single NativeScript plugin that you can install into any existing NativeScript application. For this article’s examples, let’s start by creating a new, blank NativeScript app using the NativeScript CLI’s tns create command:

tns create my-app --template tns-template-blank cd my-app

Note: The create command’s

--template flag creates a NativeScript app from an existing template. Refer to “Starting NativeScript Apps From Templates” for more information on the option, and for a full list of templates available.

Now that you have a new NativeScript project scaffolded, you’re ready to add in UI for NativeScript. UI for NativeScript has two separate distributions, a free distribution that is available on npm – containing theRadSideDrawer andRadListView components — and a premium distribution, containing the free controls, as well as the premiumRadChart andRadCalendar components.

Regardless of which distribution you’re using, you need to use the NativeScript CLI’s tns plugin add to add the plugin to your project. For this tutorial we’ll be using the free controls exclusively, so run the command below to install the free distribution from npm:

tns plugin add nativescript-telerik-ui

Note: For more information on installing the premium controls, refer to the installation instructions on the Telerik UI for NativeScript documentation .

After running tns plugin add , if you check your project’s package.json file you should see a new dependency on “nativescript-telerik-ui”, indicating that you’re ready to start using UI for NativeScript in your app.

"dependencies": {   "nativescript-telerik-ui": "1.0.0",   ... }

With the installation out of the way, let’s look at a few of the things you can do.

RadSideDrawer

The side drawer user interface control has become commonplace in mobile app development. Sometimes the control is used to implement an app’s navigation, and sometimes it’s used to show a menu or additional UI controls. Regardless of which of these scenarios you need in your next app, the UI for NativeScript RadSideDrawer control makes the implementation trivial. Let’s look at how it works.

Basic side drawer navigation

The most common use of a side drawer component is for navigation. To see how it works, let’s look at how to implement the UI below using a RadSideDrawer control.

Building Polished Mobile Apps with Telerik UI for NativeScript Building Polished Mobile Apps with Telerik UI for NativeScript

Start by opening your new project’s main-page.xml and pasting in the following code:

<Page   xmlns="http://schemas.nativescript.org/tns.xsd"   xmlns:drawer="nativescript-telerik-ui/sidedrawer"   loaded="loaded">    <drawer:RadSideDrawer id="drawer">      <!-- The main content -->     <drawer:RadSideDrawer.mainContent>       <StackLayout>         <Button text="Toggle Drawer" tap="toggleDrawer" />       </StackLayout>     </drawer:RadSideDrawer.mainContent>      <!-- The drawer content -->     <drawer:RadSideDrawer.drawerContent>       <GridLayout class="drawer-content">         <StackLayout>           <Label text="Home" />           <Label text="About" />           <Label text="Settings" />         </StackLayout>       </GridLayout>     </drawer:RadSideDrawer.drawerContent>    </drawer:RadSideDrawer> </Page>

When you use a RadSideDrawer you must divide your page into two sections—the content that should appear in the drawer ( <drawer:RadSideDrawer.drawerContent> ), and the content that should appear in the main part of the page ( <drawer:RadSideDrawer.mainContent> ). In the code above, you place a single button in the main content, and three labels in the app’s drawer.

Your next step is to implement the JavaScript code to toggle the display of the drawer when you click the app’s button. To do so, open your app’s main-page.js file and paste in the following code:

var drawer;  exports.loaded = function(args) {   var page = args.object;   drawer = page.getViewById("drawer"); }; exports.toggleDrawer = function() {   drawer.toggleDrawerState(); };

This file contains two event handlers. You use the page’s loaded event to get a reference to the current page object , and the button’s tap handler to call the RadSideDrawer’s toggleDrawerState() method, which opens and closes the app’s drawer.

After this change, if you run your app you should now have a functioning drawer. However, because the drawer has no background or styling, the drawer’s three labels awkwardly sit on top of the main content:

Building Polished Mobile Apps with Telerik UI for NativeScript

It’s easy to fix this, as drawers are styleable just like any other NativeScript UI component. To make the drawer look like gifs above, open up your app’s app.css and paste in the following code:

.drawer-content {   background-color: #053140;   color: white;   padding-top: 20; } .drawer-content Label {   font-size: 20;   margin: 10 0 15 25; } 

Tip: If you’d like, take a few minutes and use any of NativeScript’s supported CSS properties to change this drawer to match the look of your own apps.

With this, you now have a functioning drawer that works cross-platform on iOS and Android—all in about 40 lines of XML, JavaScript, and CSS.

Building Polished Mobile Apps with Telerik UI for NativeScript Building Polished Mobile Apps with Telerik UI for NativeScript

Now that you have the basics down, let’s look at some of the other things you can do with the RadSideDrawer control.

Implementing an options menu

Although the RadSideDrawer is most commonly used for a navigation menu, there are a variety of other things you can do with the control. In this section we’ll look at how to use a RadSideDrawer to implement the following options menu:

Building Polished Mobile Apps with Telerik UI for NativeScript Building Polished Mobile Apps with Telerik UI for NativeScript

Start by pasting the following code into your main-page.xml file, which should look pretty similar to the XML code you used earlier:

<Page   xmlns="http://schemas.nativescript.org/tns.xsd"   xmlns:drawer="nativescript-telerik-ui/sidedrawer"   loaded="loaded">    <drawer:RadSideDrawer id="drawer" drawerLocation="Bottom"     drawerContentSize="110">      <!-- The main content -->     <drawer:RadSideDrawer.mainContent>       <StackLayout>         <Button text="Toggle Drawer" tap="toggleDrawer" />         <Label text="{{ 'You selected: ' + selected }}" />       </StackLayout>     </drawer:RadSideDrawer.mainContent>      <!-- The drawer content -->     <drawer:RadSideDrawer.drawerContent>       <stack-layout class="drawer-content">         <label text="Option 1" tap="select" />         <label text="Option 2" tap="select" />       </stack-layout>     </drawer:RadSideDrawer.drawerContent>    </drawer:RadSideDrawer> </Page>

The one big difference to note here is the use of the drawerLocation and drawerContentSize attributes, which are used to place the drawer on the bottom of the screen, and to set the drawer’s height, respectively.

Tip: drawerTransition is another commonly used RadSideDrawer attribute. You can use the attribute to control how the drawer appears relative to the main content.Refer to the docs for a full list of the values you can use for drawerTransition .

To make this drawer work as expected, the only addition to the page’s JavaScript is a bit of code that uses NativeScript’s data binding implementation to show the selected option on the screen. Paste the following code into your main-page.js file to see the example working for yourself:

var Observable = require("data/observable").Observable; var pageData; var drawer;  exports.loaded = function(args) {   var page = args.object;   pageData = new Observable({ selected: "Nothing" });   page.bindingContext = pageData;   drawer = page.getViewById("drawer"); }; exports.toggleDrawer = function() {   drawer.toggleDrawerState(); }; // This is the code that runs when the user clicks on one of the // options in the menu. The code sets the “selected” property on // the page’s data model, and NativeScript’s data binding // implementation takes care of the rest. exports.select = function(args) {   pageData.set("selected", args.view.text);   drawer.closeDrawer(); };

Finally, to get your app looking like the gifs above, paste the following CSS in your app.css file, or use some alternative CSS to customize the look of the drawer yourself.

.drawer-content {   background-color: #311217;   color: white; } .drawer-content label {   margin: 16;   font-weight: bold; }

And with that little bit of code, you now you have a functioning menu you can use to select options or actions from:

Building Polished Mobile Apps with Telerik UI for NativeScript Building Polished Mobile Apps with Telerik UI for NativeScript

Regardless of how you choose to use your RadSideDrawer, you’re likely going to run into one common question right away — how do you share your drawer content on multiple pages of your application?

Sharing a drawer across pages

The RadSideDrawer was designed to be a child of a <Page> element, and not as a component that could be at the root of the entire application. This gives developers the flexibility to use different drawers on the different pages, and to omit the usage of a drawer on certain pages if desired.

However, if you’re using a RadSideDrawer as your app’s main navigation, you probably don’t want to duplicate the code needed to build the same drawer on each and every page in your app. Luckily, NativeScript makes it easy to share this code by creating a new custom UI component .

To see how this works, let’s build a small example where you can navigate between two pages. At the end the app will look like this:

Building Polished Mobile Apps with Telerik UI for NativeScript Building Polished Mobile Apps with Telerik UI for NativeScript

Start by adding three new files you your app: other-page.js , other-page.xml , and shared/drawer.xml . The folder structure of your app should look like this:

. ├── app.css ├── app.js ├── main-page.js ├── main-page.xml ├── other-page.js ├── other-page.xml └── shared     └── drawer.xml 

Below are copy-and-paste friendly versions of each of these files. Start by pasting the updated versions in, and then we’ll take a step back and see how this code could be improved.

  • app.css
.drawer-content {   background-color: #053140;   color: white;   padding-top: 20; } .drawer-content Label {   font-size: 20;   margin: 10 0 15 25; }
  • app.js
var application = require("application"); application.cssFile = "./app.css"; application.start({ moduleName: "main-page" });
  • main-page.js and other-page.js (use the exact same code for now)
var topmost = require("ui/frame").topmost; var drawer;  exports.loaded = function(args) {   var page = args.object;   drawer = page.getViewById("drawer"); }; exports.toggleDrawer = function() {   drawer.toggleDrawerState(); }; exports.navigate = function(args) {   var pageName = args.view.text;   topmost().navigate(pageName == "Main Page" ? "main-page" : "other-page"); };
  • main-page.xml
<Page   xmlns="http://schemas.nativescript.org/tns.xsd"   xmlns:drawer="nativescript-telerik-ui/sidedrawer"   xmlns:shared="shared"   actionBarHidden="true"   loaded="loaded">    <drawer:RadSideDrawer id="drawer">      <!-- The main content -->     <drawer:RadSideDrawer.mainContent>       <StackLayout>         <Label text="Main page" />         <Button text="Toggle Drawer" tap="toggleDrawer" />       </StackLayout>     </drawer:RadSideDrawer.mainContent>      <!-- The drawer content -->     <drawer:RadSideDrawer.drawerContent>       <shared:drawer />     </drawer:RadSideDrawer.drawerContent>    </drawer:RadSideDrawer> </Page>
  • other-page.xml
<Page   xmlns="http://schemas.nativescript.org/tns.xsd"   xmlns:drawer="nativescript-telerik-ui/sidedrawer"   xmlns:shared="shared"   actionBarHidden="true"   loaded="loaded">    <drawer:RadSideDrawer id="drawer">      <!-- The main content -->     <drawer:RadSideDrawer.mainContent>       <StackLayout>         <Label text="Other page" />         <Button text="Toggle Drawer" tap="toggleDrawer" />       </StackLayout>     </drawer:RadSideDrawer.mainContent>      <!-- The drawer content -->     <drawer:RadSideDrawer.drawerContent>       <shared:drawer />     </drawer:RadSideDrawer.drawerContent>    </drawer:RadSideDrawer> </Page>
  • drawer.xml
<GridLayout class="drawer-content">   <StackLayout>     <Label text="Main Page" tap="navigate" />     <Label text="Other Page" tap="navigate" />   </StackLayout> </GridLayout> 

The key thing to notice is the use of <shared:drawer /> in both the main-page.xml and other-page.xml files. This line of code points the NativeScript parser at the code snippet in shared/drawer.xml , which contains the two labels that you’re now sharing between your two pages. The one big downside of the code thus far, as you might have noticed, is that there’s still a whole lot of code duplication here—particularly in the JavaScript files, which are identical for each page.

There are a number of techniques you could use in JavaScript to help eliminate this duplication, including putting the common code in a shared module, or creating a base page that all of your pages inherit from. A full discussion of that is out of scope for this article, however, if you’re looking for an approach that just works out of the box, you can try starting your next NativeScript app from the NativeScript drawer template by running the command below:

tns create my-app --template nativescript-template-drawer

Or if you prefer to develop in TypeScript, you can alternatively use the TypeScript version of the same template with the command below:

tns create my-app --template nativescript-template-drawer-ts

As you can see, UI for NativeScript makes building powerful interfaces as simple as using a few JavaScript and XML APIs. And we’re just getting started! Now that we’ve looked at some of the most common use cases of the RadSideDrawer, let’s look at what you can do with the other free control included in UI for NativeScript—RadListView.

RadListView

The Telerik RadListView is essentially a NativeScript ListView++. In addition to supporting everything the NativeScript ListView can do, the RadListView adds several additional, powerful features. Let’s see how it works by building a few examples.

Implementing pull to refresh

List views are incredibly common in mobile apps today, and one of their most commonly used features is the pull-to-refresh interaction. To see how it works, let’s look at how to build the gifs below using a RadListView control:

Building Polished Mobile Apps with Telerik UI for NativeScript Building Polished Mobile Apps with Telerik UI for NativeScript

Let’s start by getting a basic RadListView up and running. To do that, open up your main-page.xml file and paste in the following code:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:lv="nativescript-telerik-ui/listview" loaded="loaded">    <ActionBar title="RadListView" />    <lv:RadListView id="list-view" items="{{ items }}">     <lv:RadListView.listViewLayout>       <lv:ListViewLinearLayout scrollDirection="Vertical" />     </lv:RadListView.listViewLayout>      <lv:RadListView.itemTemplate>       <Label text="{{ name }}" />     </lv:RadListView.itemTemplate>   </lv:RadListView>  </Page>

If you’ve worked with a NativeScript ListView before, most of this code will look familiar. To get a basic <RadListView> working, you need to point its items property at an ObservableArray (which we’ll look at in a minute), and also provide an itemTemplate that defines how NativeScript should render each individual item on the screen. In this case, you’re using a simple <Label> element to display each item’s name property.

Note: The listViewLayout property determines how the RadListView should arrange its items on the screen. The examples used in this article will all use a linear layout as it’s the most common, but you can learn about other layout types on the UI for NativeScript docs .

Next, implement the JavaScript side of this example by opening up your main-page.js file and pasting in the following code:

var Observable = require("data/observable").Observable; var ObservableArray = require("data/observable-array").ObservableArray;  var page; var items = new ObservableArray([]); var pageData = new Observable();  exports.loaded = function(args) {   page = args.object;   page.bindingContext = pageData;    // Toss a few numbers in the list for testing   items.push({ name: "1" });   items.push({ name: "2" });   items.push({ name: "3" });    pageData.set("items", items); };

Note the tie between the "items" property you’re using in JavaScript, and the items="{{ items }}" attribute you’re using on the <RadListView> in your XML code. With this tie in place, NativeScript automatically takes changes you make to the items array in JavaScript and displays them in your application. So when you call push on the array in the loaded() function, those values automatically render in your RadListView control. You can see this if you run your application with these updates in place:

Building Polished Mobile Apps with Telerik UI for NativeScript Building Polished Mobile Apps with Telerik UI for NativeScript

Now that you have a basic list ready, let’s add the pull-to-refresh interaction. Open your main-page.xml file again and add two new attributes to the <RadListView> element: pullToRefresh="true" , which is a boolean that turns on the control’s pull-to-refresh handling, and pullToRefreshInitiated="pullToRefreshInitiated" , which is an event handler NativeScript invokes when the user performs the pull-to-refresh gesture (swiping down from the top of the list). We’ll define that function in JavaScript momentarily. For now, here’s a copy-and-paste friendly version what the full main-page.xml file should look like:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:lv="nativescript-telerik-ui/listview" loaded="loaded">    <ActionBar title="RadListView" />    <lv:RadListView items="{{ items }}" pullToRefresh="true" pullToRefreshInitiated="pullToRefreshInitiated">     <lv:RadListView.listViewLayout>       <lv:ListViewLinearLayout scrollDirection="Vertical" />     </lv:RadListView.listViewLayout>      <lv:RadListView.itemTemplate>       <label text="{{ name }}" />     </lv:RadListView.itemTemplate>   </lv:RadListView>  </Page>

Next, open up your main-page.js file, and paste this new function at the bottom of the file:

exports.pullToRefreshInitiated = function() {   // Simulate a call to a backend that comes back two seconds later   setTimeout(function() {     items.push({ name: "4" });     page.getViewById("list-view").notifyPullToRefreshFinished();   }, 2000); };

Now, when the user initiates a pull-to-refresh gesture, the RadListView first automatically shows a platform-specific loading indicator, and then invokes your pullToRefreshInitiated event handler. Your job in pullToRefreshInitiated is to make any necessary changes to your array of data, and then to call the notifyPullToRefreshFinished() method to tell NativeScript to take down the loading indicator.

In this case of the code above, you’re adding a single hardcoded item to the list after two seconds. In a more realistic scenario, you would probably check your backend API to see if any changes had been made, and add or remove the appropriate data entries as necessary. The app with this sample code looks like this in action:

Building Polished Mobile Apps with Telerik UI for NativeScript Building Polished Mobile Apps with Telerik UI for NativeScript

Tip: Notice how the “4” item in the gifs below suddenly appears on the screen? You can add a bit of polish to this UI by adding one of the RadListView’s built-initem animations.

Hopefully this example gives you a sense of just how simple RadListView makes implementing some relatively complex interactions with straightforward JavaScript and XML APIs. Let’s look at one more of these: swipe to execute.

Adding swipe-to-execute actions

Initially popularized by iOS, swipe-to-execute actions are becoming a popular way to allow users to perform actions on list view items. In this section we’ll look at how to use the RadListView to implement the following interface:

Building Polished Mobile Apps with Telerik UI for NativeScript Building Polished Mobile Apps with Telerik UI for NativeScript

Paste the code below in your main-page.xml file first, and then we’ll break down how it all works.

<Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:lv="nativescript-telerik-ui-pro/listview" loaded="loaded">    <ActionBar title="RadListView" />    <lv:RadListView id="list-view" items="{{ items }}"     swipeCells="true"     itemSwipeProgressStarted="itemSwipeProgressStarted"     itemSwipeProgressEnded="itemSwipeProgressEnded">      <lv:RadListView.listViewLayout>       <lv:ListViewLinearLayout scrollDirection="Vertical" />     </lv:RadListView.listViewLayout>      <lv:RadListView.itemTemplate>       <GridLayout backgroundColor="white">         <Label text="{{ name }}" class="{{ complete ? 'line-through' : '' }}" />       </GridLayout>     </lv:RadListView.itemTemplate>      <lv:RadListView.itemSwipeTemplate>       <GridLayout columns="100 *, 100">         <StackLayout col="0" backgroundColor="green">           <Label text="Check" color="white" />         </StackLayout>         <StackLayout col="2" backgroundColor="red">           <Label text="Delete" color="white" />         </StackLayout>       </GridLayout>     </lv:RadListView.itemSwipeTemplate>    </lv:RadListView>  </Page>

There are two new things in this code to note. The first is the new attributes on the <RadListView> element: swipeCells , itemSwipeProgressStarted , and itemSwipeProgressEnded . Much like the pull-to-refresh example, the first attribute ( swipeCells ) is a boolean that turns the feature on, and the other attributes ( itemSwipeProgressStarted and itemSwipeProgressEnded ) define JavaScript functions to handle events associated with that feature. Before we move onto defining those event handlers in JavaScript, notice the other new chunk of code:

<lv:RadListView.itemSwipeTemplate>   <GridLayout columns="100 *, 100">     <StackLayout col="0" backgroundColor="green">       <Label text="Check" color="white" />     </StackLayout>     <StackLayout col="2" backgroundColor="red">       <Label text="Delete" color="white" />     </StackLayout>   </GridLayout> </lv:RadListView.itemSwipeTemplate>

When you use the RadListView’s swipeCells feature, you have to provide a template for the content that lives behind the main content. Visually, it may help to picture the RadListView’s itemTemplate sitting directly on top of its itemSwipeTemplate . When the user starts to swipe the itemTemplate content to the left or to the right, the itemSwipeTemplate determines the content the shows beneath it. In this case, you define two <StackLayout> elements — one with a green background and one with a red background — and use a <GridLayout> to place the green <StackLayout> on the left-hand side of the RadListView, and the red <StackLayout> on the right-hand side of the RadListView.

If you were to try your app at this point, you’d have the ability to swipe items side to side, but doing so wouldn’t actually have any effect.

Building Polished Mobile Apps with Telerik UI for NativeScript

To make these swipe actions actually do something, we have to define a few event handlers in our JavaScript code. Open your main-page.js file and paste in the following code:

var Observable = require("data/observable").Observable; var ObservableArray = require("data/observable-array").ObservableArray; var utilsModule = require("utils/utils");  var page; var items = new ObservableArray([]); var pageData = new Observable();  exports.loaded = function(args) {   page = args.object;   page.bindingContext = pageData;    // Toss a few items in the list for testing   items.push({ name: "Clean house", complete: false });   items.push({ name: "Do laundry", complete: false });   items.push({ name: "Wash dog", complete: false });    pageData.set("items", items); };  function getSwipeThreshold() {   return 100 * utilsModule.layout.getDisplayDensity(); }  exports.itemSwipeProgressStarted = function(args) {   var swipeLimits = args.data.swipeLimits;   swipeLimits.threshold = getSwipeThreshold();   swipeLimits.left = getSwipeThreshold();   swipeLimits.right = getSwipeThreshold(); }; exports.itemSwipeProgressEnded = function(args) {   var item = items.getItem(args.itemIndex);    if (args.data.x <= -(getSwipeThreshold())) {     items.splice(args.itemIndex, 1);   }   if (args.data.x >= getSwipeThreshold()) {     item.complete = !item.complete;     // Clone the item so {N}’s change detection picks up the      // change and updates the list.     items.setItem(args.itemIndex, Object.assign({}, item));   } };

The two new things in this file are the itemSwipeProgressStarted and itemSwipeProgressEnded event handlers. As their names imply, the itemSwipeProgressStarted event runs when the user starts a swipe action, and the itemSwipeProgressEnded event runs when the user completes a swipe action.

In itemSwipeProgressStarted you need to set three properties on a provided swipeLimits object:

  • threshold determines how long a user needs to swipe before the itemSwipeProgressEnded event triggers.
  • left determines how far the user should be able to swipe a cell from left to right.
  • right determines how far the user should be able to swipe a cell from right to left.

Finally, in itemSwipeProgressEnded you use the RadListView-provided args.data.x value to determine how far the user has swiped. If the user has exceeded the left threshold, you delete the item from the list, and if the user has exceeded the right threshold, you change the item’s complete flag, which determines whether the item appears checked out or not.

To make that last change actually appear, paste the following code in your app.css file, as the XML uses the line-through CSS class name to implement the strike through:

Label {   margin: 15; } .line-through {   text-decoration: line-through; }

And with that, our swipe-to-execute example is complete:

Building Polished Mobile Apps with Telerik UI for NativeScript Building Polished Mobile Apps with Telerik UI for NativeScript

There are several different ways you can configure swipe-to-execute actions using the RadListView. You can allow the user to swipe top to bottom (or bottom to top); you can allow swipes from only one direction, you can make items “stick” to a given swipe position; and a whole lot more. Refer to the RadListView docs on swipe-to-execute for more information on what’s possible.

Wrapping up

Hopefully this gives you an idea of all that you can accomplish with Telerik UI for NativeScript. And we’ve only scratched the surface! There are numerous additional options for both RadSideDrawer and RadListView, as well as the premium RadChart and RadCalendar controls. Make sure to refer both to both the UI for NativeScript homepage , as well as the UI for NativeScript documentation for more information.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Building Polished Mobile Apps with Telerik UI for NativeScript

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮