Our First Sample - Part 3

 

Introduction

This blog post will be featuring ways to interact with the user via the User Interface. The ways that we will be discussing today are Notifications from the Notification Bar, Toast messages, and the View Animator. All of these different components will be combined to give the User a unique experience. This post is again part of a multipart series in which we cover various Android lessons. If you haven't taken a look at the first and second parts of this post, I highly recommend you do as these will be extending the previous examples.

Getting Started

In both of the previous examples, we constructed the User Interface by creating a new Text View and setting the context to be that of the Text View. In this example we are going to be using an XML to define what elements the User will see. This method of using the XML to create the User Interface is the Android way. Later in this blog post, we will create our own XML layout file.

Old way of setting up User Interface
1private TextView textview = null;
2textview = new TextView(this);
3textview.setText("Counter Sample");
4setContentView(textview);


Toast Messages

A Toast message is a simple, unobtrusive popup that hovers above your application. Toast messages are very simple to make. For instance, we already have the notion of a "trigger" but perhaps we want to display a message that alerts the user whenever the "trigger" goes off.

Within onReceive() in CounterUISample.java
1if(type.equals("trigger")) {
2    Toast.makeText(CounterUISample.this, "Alert!", Toast.LENGTH_SHORT).show();
3}

In order to make the Toast message, you need a context in which to display it from, the text, and the length of how long it should be displayed. You then go on to tell the Toast to display the method by calling show. At this point, your application should run and display the alert every time the trigger goes off.

Notifications

A Notification is a simple message that will show up in the Notification Bar of Android. In order to use a Notification you must have a Notification Manager which simply tells Android when to display the Notification or when to remove it. In this case, we will display a Notification when the Counter starts running and remove the Notification when the counter is no longer running.

  • Line 4: Create a Notification Manager
  • Line 5: Create a unqiue ID to identify the Notification
  • Line 14: Connect the Notification Manager to the Android Notification Service
  • Line 15: Create a Notification that will be displayed by the Manager
  • Line 16: Create a PendingIntent that will launch our application if the Notification is clicked
  • Line 17: Set the Notification and PendingIntent as the LastestEventInfo
  • Line 18: Set the Flag so that this will be considered an Ongoing Event
  • Line 19: Display this Notification when created
  • Line 25: Removed this Notification when the counter stops
CounterService.java
 1public class CounterService extends Service {
 2    
 3    private Counter counter = null;
 4    private NotificationManager nM;
 5    final int ID = 1;
 6    
 7    public CounterService() {
 8        this.counter = new Counter(3, 10, this);
 9    }
10
11    @Override
12    public void onCreate() {
13        counter.start();
14        nM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
15        Notification notification = new Notification(R.drawable.icon, "Counter is running.", System.currentTimeMillis());
16        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, CounterUISample.class), 0);
17        notification.setLatestEventInfo(this, "Counter", "The Counter is currently running.", contentIntent);
18        notification.flags = Notification.FLAG_ONGOING_EVENT;
19        nM.notify(ID, notification);
20    }
21    
22    @Override
23    public void onDestroy() {
24        counter.stop();
25        nM.cancel(ID);
26    }    
27    
28    @Override
29    public IBinder onBind(Intent intent) {
30        return null;
31    }
32}

As you can see, this starts the Notification when the counter starts and ends the notification when the counter stops. At this point the application should be runnable and you will notice the notification starting and stopping when the program does.

Constructing the XML

In previous examples, the User Interface has always been created by Java code in the onCreate method. This however, is not the typical Android way of doing things. Generally in Android the User Interface is setup in a XML file. This XML file will contain the placement and other various attributes to define what the User Interface will look like. Then in Java code you are able to reference the parts and fill them in with actual data. Below is a XML file that will layout our User Interface.

main.xml
 1<?xml version="1.0" encoding="utf-8"?>
 2<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3    android:orientation="vertical"
 4    android:layout_width="fill_parent"
 5    android:layout_height="fill_parent"
 6    >
 7<ViewAnimator android:id="@+id/views"
 8        android:layout_width="match_parent"
 9        android:layout_height="wrap_content"
10        android:layout_marginBottom="20dip" >
11                <TextView
12                        android:id="@+id/text1"
13                        android:layout_width="match_parent"
14                        android:layout_height="wrap_content"
15                        android:gravity="center_horizontal"
16                        android:textSize="100sp"/>
17                <TextView
18                        android:id="@+id/text2"
19                        android:layout_width="match_parent"
20                        android:layout_height="wrap_content"
21                        android:gravity="center_horizontal"
22                        android:textSize="100sp"/>
23    </ViewAnimator>
24</LinearLayout>

In this we create a Linear Layout that will show our information on the screen in vertical order. We then make a View Animator which will contain the two Text Views that we will be switching back and forth to.

View Animator

A View Animator is simply a way to transition between views. It can contain some animation so that the transitions between views are smooth and more pleasurable to the eye. In this case, we want to display the a number as a Text View that will transition to the next Text View which will contain the next number. However, we do not have a predefined number of Text Views to transition to or want to create every possible Text View. In order to counter act this problem, we will have only two Text Views. All we have to do is transition to the Text View that is not being displayed at the moment and set the text to the next number coming up. 

  • Line 1-3: Create the Text Views and a View Animator
  • Line 4: Create a Boolean variable to toggle back and forth
Within CounterUISample.java
1public TextView text1;
2public TextView text2;
3public ViewAnimator animator;
4private boolean toggle = true;

  • Line 1: Instantiate the View Animator by connecting it to our XML
  • Line 2-3: Set the In and Out Animation for the Animator (We will discuss this more in a second)
  • Line 4-5: Instantiate Text Views by connecting them to our XML
  • Line 6: Set the first one to zero, as we know this is the starting point
Within onCreate() of CounterUISample.java
1animator = (ViewAnimator)findViewById(R.id.views);
2animator.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.push_up_in));
3animator.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.push_up_out));    
4text1 = (TextView)findViewById(R.id.text1);
5text2 = (TextView)findViewById(R.id.text2);
6text1.setText("0");

  • Line 2, 5, 9: Setup the toggle so that it goes back and forth "hitting" true then false within the loop
  • Line 3, 7: Set the text of the next Text View to be the next number
  • Line 4, 8: Animate to the Text View that you just altered
Within onReceive() of CounterUISample.java
 1if (value != null) {
 2    if(toggle) {
 3        text2.setText(Integer.toString(value));
 4        animator.showNext();
 5        toggle = false;
 6    } else {
 7        text1.setText(Integer.toString(value));
 8        animator.showPrevious();
 9        toggle = true;
10    }
11}

The next step is to take a look at the actual animation that will be performed on these Views. 

Tween Animation

A Tween Animation is very simple way of defining animations. It contains sets, or groups of animation to be completed at the same time. A set can contain the following types: alpha, scale, translate, and rotate. Each of these has its own variables that need to be filled out.

We need to create a folder under the res folder called anim. This folder will contain our animations. Then create two xml files called push_up_in.xml and push_up_out.xml. The animation files I am listing were distributed by Android, but are a good place to start when learning how to write XML animation files.

push_up_in.xml
1<set xmlns:android="http://schemas.android.com/apk/res/android">
2    <translate android:fromYDelta="100%" android:toYDelta="0" android:duration="1000"/>
3    <alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="1000" />
4</set>

push_up_out.xml
1<set xmlns:android="http://schemas.android.com/apk/res/android">
2    <translate android:fromYDelta="0" android:toYDelta="-100%" android:duration="1000"/>
3    <alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="1000" />
4</set>

In this example, we used translate and alpha. For translate we tell it to go from some point to another point with a set duration. For alpha we tell it to go from transparent to opaque with a set duration. Once, we have these Tween animations we can run the project and see how the User Interface has been greatly improved by using a simple View Animator.

Conclusion

In this blog post, we were able to cover a few different areas:

  • Toasts
  • Notifications
  • View Animators
  • Tween Animations

By MatthewT Williams

 

Subscribe to our Cius Developer Blog RSS feed to get the latest info and sample code.