jQuery mobile: Page loading widget

Hey everyone!

jQuery mobile provides a navigation system that can display pages with a set of animated transitions. Now, developers can add various transitions including fade, pop, flip, turn etc to their web pages. However, when you carry out a background task that consumes a lot of time, it is advisable to display a Page Loading widget. This widget handles the task of displaying the loading dialog.

Here is a short demo of the Page loading widget!

test.html


<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>

<script type="text/javascript">

function showIndicator(){
$.mobile.loading( 'show', {
	text: 'Loading...',
	textVisible: true,
	theme: 'b',
	html: ""
   });
}

function hideIndicator(){
$.mobile.loading( 'hide');
}

</script>

</head>
<body>

<input type="button" value="Click me" onclick="showIndicator();"/>
<input type="button" value="Hide me" onclick="hideIndicator();"/>

</body>
</head>

</html>

The result looks something like this,

output

Note: The page loading dialog was previously configured globally with three settings $.mobile.loadingMessage, $.mobile.loadingMessageTextVisible, and $.mobile.loadingMessageTheme which are now deprecated. In addition to the methods for showing and hiding, $.mobile.showPageLoadingMsg and $.mobile.hidePageLoadingMsg are also deprecated.

Source: jQuery mobile website

Learning Kivy: Bubble

Hello friends!

Today, we will learn about a very simple yet fascinating Kivy widget called Bubble. The Bubble widget is basically a small pop up that appears and consists of menu options that are stacked either horizontally or vertically.

Every Bubble widget contains an arrow pointing towards the direction you choose. By default the direction is ‘bottom_mid’ i.e bottom middle.

A Bubble widget can be implemented as:

bubble = Bubble(orientation = 'vertical')
#Add items to the Bubble
bubble.add_widget(your_widget_instance)

What is a BubbleButton?

It is basically a button intended for use as in a Bubble widget. Using BubbleButton you can use the background that has been already defined. On the other hand if you stick to Bubble then you need to customize it in order to change the background image, color etc.

Customizing your bubble

You can change the background color, image and border of the Bubble. You can also add an image for the arrow as follows:

bubble.background_color = (1, 0, 0, .5) #50% translucent red
bubble.border = [0, 0, 0, 0]
background_image = 'path/to/background/image'
arrow_image = 'path/to/arrow/image'

So now let’s begin implementing the Bubble widget!

Open Python IDLE. Create a new Python script named bubbledemo.py and write the following code!

bubbledemo.py

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.bubble import Bubble
from kivy.uix.bubble import BubbleButton

class MyBubbleApp(App):
    def build(self):
        
        root= GridLayout()
        layout = FloatLayout(orientation='horizontal', size=(150,100), size_hint=(None, None))
        my_btn=Button(text='Press to view bubble',pos=(300,300),on_press=show_bubble)
        layout.add_widget(my_btn)
        root.add_widget(layout)
        return root

def show_bubble(self,*args):
        my_bubble= Bubble(orientation = 'horizontal',pos=(280,400))
        #Customizing my bubble
        my_bubble.background_color =(20, 0, 0, .5) 
        my_bubble.border = [50, 50, 50, 10]
        my_bubble.arrow_pos= 'top_left'
        my_bub_btn1= BubbleButton(text='Copy',size_hint=(None, None),size=(80, 50),pos=(200,400)) 
        my_bub_btn2= BubbleButton(text='Cut',size_hint=(None, None),size=(80, 50),pos=(300,400))
        my_bub_btn3= BubbleButton(text='Paste',size_hint=(None, None),size=(80, 50),pos=(300,400))
        #Add items to bubble
        my_bubble.add_widget(my_bub_btn1)
        my_bubble.add_widget(my_bub_btn2)
        my_bubble.add_widget(my_bub_btn3)
        self.add_widget(my_bubble)
        
      
if __name__ == '__main__':
    MyBubbleApp().run()

Run the above script by typing kivy bubbledemo.py inside the command prompt and you should see the following output!

Output

bubble_demo_2

Learning Kivy: Accordion

Hey everyone!

Working on Kivy has been an amazing learning experience. Kivy has made user interface development a lot easier. Today, I will talk about Accordion, one of the interesting widgets that Kivy has to offer to developers out there.

Accordion

Accordion is basically a Widget in the form of a menu where in the options are stacked either horizontally or vertically. An Accordion will contain one or many AccordionItem instances such that each item when touched opens up displaying it’s underlying content.

The current implementation divides the AccordionItem into two parts:
1. One container for the title bar
2. One container for the content

The title bar is made from a Kv template. In order to customize the title bar you need to design your own template.

The current default template is present in the kivy/data/style.kv file.

Here is a small implementation of the code required to build your own template that I found in the Kivy docs.

[AccordionItemTitle@Label]:
    text: ctx.title
    canvas.before:
        Color:
            rgb: 1, 1, 1
        BorderImage:
            source:
                ctx.item.background_normal \
                if ctx.item.collapse \
                else ctx.item.background_selected
            pos: self.pos
            size: self.size
        PushMatrix
        Translate:
            xy: self.center_x, self.center_y
        Rotate:
            angle: 90 if ctx.item.orientation == 'horizontal' else 0
            axis: 0, 0, 1
        Translate:
            xy: -self.center_x, -self.center_y
    canvas.after:
        PopMatrix

Now, let’s start creating a simple Kivy app that displays an Accordion widget. Open Python IDLE. Create a new file named Accordion.py and start writing the following code!

In this example, I will be displaying images as my content when the user touches an item. For each item a different image would exist!

Accordion.py

from kivy.uix.accordion import Accordion, AccordionItem
from kivy.uix.image import Image
from kivy.app import App

class SampleAccorApp(App):
    def build(self):
        # you can change orientation to horizontal as well
        root = Accordion(orientation='vertical')
        for x in xrange(5):
            item= AccordionItem(title='Image %d' %x)
            src = "images/%d.jpg" % x
            image = Image(source=src,pos=(400, 100), size=(400, 400))
            # add image to AccordionItem
            item.add_widget(image)
            root.add_widget(item)
        return root

if __name__ == '__main__':
    SampleAccorApp().run()

Run the above code by writing kivy Accordion.py inside command prompt.

Accordion output

Output

Output

As compared to Accordion, the AccordionItem is more configurable and customizable. For example, you can set your own title background when the item is collapsed or opened.

    item = AccordionItem(background_normal='image_when_collapsed.png',
    background_selected='image_when_selected.png')

So, that’s it for this tutorial. Hope it helps you in some way! Thanks 🙂

Tutorial #17: AnalogClock Widget in Android

Hello!

I have been meaning to write this post for a long time now! Recently, I was working on a project where I needed to add an AnalogClock to my home screen in Android. After having gone through the Android developers guide, I got to know about the AnalogClock widget that could help me accomplish this task.

So let’s not waste any time and start implementing the clock widget!

Requirements: Android SDK, Eclipse Helios/Indigo.

Step 1: Create a new Android project in Eclipse.

Name it as AndroidAnalogClockWidget. Select Android 2.3.3 as the Target SDK.

Step 2: You need to create a layout for your widget. Create XML file called main.xml that would define the widget layout.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:layout_height="200dp"
    android:layout_width="160dp"
    android:orientation="horizontal">
  
    <AnalogClock
        android:id="@+id/analogClock1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    
</LinearLayout>

As seen from the above XML file, we now have added the Analog clock to our layout. However, we need to add an AppWidgetProvider which would help us implement our own AppWidget functionality.

Step 3: Create a folder named xml within the res folder. Create XML file called clock_widget_provider.xml inside the xml folder.

res/xml/clock_widget_provider.xml

<?xml version="1.0" encoding="utf-8" ?>
<appwidget-provider
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="146dp"
    android:initialLayout="@layout/main"
    android:updatePeriodMillis="1000"
    android:minHeight="144dp"/>

Step 4: Create an empty class named AnalogClockWidget under the src folder with package name com.example

src/com.example/AnalogClockWidget.java

package com.example;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;


public class AnalogClockWidget extends AppWidgetProvider
{
    
}

Step 5: Finally you need to make changes to your AndroidManifest.xml and add a receiver for the clock widget.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <receiver android:name=".AnalogClockWidget" android:label="AnalogClockWidget">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/clock_widget_provider" />
        </receiver>  
    </application>
</manifest>

Make sure you have no errors in your project. Run the project to see the following output!

Select Analog Clock Widget from list

analog_clock_widget_2

You can find the source code of this tutorial from over here.

Learning Kivy: Video Player and Scatter widgets

Hello everyone!

Today I would like to share with you something new that I learnt recently while working on the Kivy library. It includes a brief introduction about the Widget class in Kivy along with two sample programs that demonstrate complex UX widgets and behaviors widgets respectively.

Widget class is the base class required to create a Widget. We can add, position and clear widgets using the methods provided by the Widget API. In simpler terms, a widget is defined as an element of a graphical user interface.

Kivy includes various widgets such as:

1) Label, Button, CheckBox, Image, Progress Bar etc (called UX widgets)

2) Scatter, Stencil View (called Behaviors widgets)

3) Drop-Down List, FileChooser, Popup, Spinner, TabbedPanel, Video player etc (called Complex UX widgets)

4) Screen Manager widget

5) Grid Layout, Box Layout, Anchor Layout etc (called Layout widgets)

In this post I will talk about the Video Player and Scatter widgets.

Video Player widget:

As defined in the Kivy docs, “a Video Player widget can be used to play video and let the user control the play/pause, volume and seek. The widget cannot be customized much, because of the complex assembly of numerous base widgets”.

Here is a sample program that demonstrates the working of the Video Player widget:

Step 1: I will be using the softboy.avi video included in the Kivy samples for this purpose. You can also download a short video (.avi , .mkv) and use it. In order to display text at a specific time and duration of the video we can use annotations. An annotation file has a .jsa extension. You can find more information on annotations over here.

Step 2: You can open any editor like Notepad++ to write the code. I will be using the Python IDLE for now.

import kivy
kivy.require('1.4.0')

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.videoplayer import VideoPlayer
    
parent= Widget()
button= Button()
        
class MyApp(App):
    def build(self):
         button = Button(text='Play video', font_size=14)
         button.bind(on_press=on_button_press)  
         parent.add_widget(button) #add button 
         return parent
              
def on_button_press(self):
        video= VideoPlayer(source='softboy.avi', state='play')
        parent.add_widget(video) #add videoplayer
        return parent
    
if __name__ == '__main__':
    MyApp().run()

Step 3: Save this script as videoplayerdemo.py

Note: Make sure you have the video file (.avi), annotation file (.jsa) if any and your Python file (.py) in the same folder. Run the application from the command prompt by typing:

kivy videoplayerdemo.py

Click on the button “Play video” to start the video. Double click on the video to increase it’s size.

VideoPlayer widget snapshot 1

VideoPlayer widget snapshot 2

Scatter widget

The Scatter is a very simple widget to understand. It is basically used to build interactive widgets that can be translated, rotated and scaled with two or more fingers on a multitouch system. It acts as a container and is combined with other widgets.

Create a new Python script named scatterdemo.py and write the following code:

import kivy
kivy.require('1.4.0')

from kivy.app import App
from kivy.uix.scatter import Scatter
from kivy.uix.image import Image    

class MyApp(App):
    def build(self):
         scatter= Scatter()
         # store kivy.jpg image in same folder as the python script
         image= Image(source='kivy.jpg')
         scatter.add_widget(image) #combine image widget with scatter
         return scatter
           
if __name__ == '__main__':
    MyApp().run()

Run the application as done before and you will see an image of the Kivy logo. You can try dragging, rotating the image using the mouse.

Drag image

Rotate image

So that completes a quick look at some of the widgets in Kivy. There is still lots to learn and many more things to do! Have a great day! 🙂