Vinay Ramkrishnan

Vinay Ramkrishnan's page

Team Member - Mobile CoE
29
Aug

In the current scenario in the mobile space, there are a lot of discussions revolving around Android and its advantages and then there are those who just cannot avoid the constant comparison with the iPhone. Keeping up with the theme, now here is something that is definitely an edge for android and sure to make the iPhone users sit up and take notice. If you still haven’t guessed it, let me tell you, what  I am referring here  is the feature called widgets. For those of you who haven’t heard of widgets, this blog will give you all what you need to know.

What are Widgets?

Well, basically they are simple miniature applications/app views that can be embedded in other applications for e.g. Home screen.. I am quite sure you must be hooked up to Facebook, so say you could have a miniature view on the home screen, that allows you to post on to your wall and then constantly update you with recent likes or comments and status updates in a small scrollable view. Well this is not just a possible concept, it exists. This is exactly what a widget is. Likewise widgets exist for a variety of applications like stock market, audio manager, battery manager etc. Everything is on the home screen and you don’t even have to launch the application. The best part about a widget is, it can update itself constantly if required without you having to refresh your screen. That’s precisely as easy as it gets!!!

Now have a look at the demo snaps and then let’s get on with creating these widgets. It’s really very simple. What we are going to do is create a simple digital clock. So let’s begin!!!

Now follow these steps and you will be on your way to creating your very own widgets for the Android Application.

Step 1: Modify Android Manifest File For the Application:

What we are essentially doing here is specifying the broadcast receiver that will process the app widget updates. The meta-data tag is used to inform android about the widget provider. In this case it is located in res/xml/widget.xml. The activity tag is used to declare the activity and the event that launches it.

Have a look at the code snippet below:

<application android:icon="@drawable/icon"
                 android:label="@string/app_name"
                 android:theme="@android:style/Theme.Translucent">

		<receiver android:name=".Widget" android:label="Custom Digital Clock">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget" />
        </receiver>

        <activity android:name=".info">
        	<intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.INFO" />
            </intent-filter>
        </activity>

    </application>

Step 2: Create Widget Provider xml file as specified in the manifest:

Following  is the definition of the widget. It has only one element i.e. appwidget-provider which takes attributes specifying minimum width, height, the update frequency and the initial layout or design for the widget. Now that was simple wasn’t it!!!

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="294dip"
android:minHeight="72dip"
android:updatePeriodMillis="0"
android:initialLayout="@layout/widget"/>


Step 3: Create Layout for the Widget(widget.xml)

Now this step is pretty self explanatory. You simply have to create layout to represent the widget. Yet the Code sample is available as always for your reference.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/Widget"
 	android:layout_width="wrap_content"
	 android:layout_height="wrap_content"
 	xmlns:android="http://schemas.android.com/apk/res/android">

 <TextView android:textColor="@android:color/primary_text_dark"
	android:padding="10dip"
	android:textSize="35dip"
	android:layout_width="wrap_content"
	android:text="12.30.35 PM"
	android:layout_gravity="center_horizontal"
	android:typeface="monospace"
	android:textStyle="bold"
	android:layout_marginRight="3dip"
	android:background="@null"
	android:layout_marginBottom="3dip"
	android:layout_marginLeft="3dip"
	android:id="@+id/widget_textview"
	android:layout_height="wrap_content"
	android:layout_marginTop="3dip"/>

</RelativeLayout>

Step 4: Create Widget Provider Class

Don’t get alarmed by the name here, it’s very simple. All you need to do is create a class that extends the AppWidgetProvider class. This is the same provider specified in the manifest file as the receiver.

The onUpdate() method needs to be overridden to include the necessary code to update time, which can be easily done using the TimerTask class in the java.util package and then it can be represented in a text view as per layout.

The onUpdate() method is called whenever an update is to be performed. Additionally pending Intents may be used to configure action to be performed on click of the widget. In this case the widget will display a simple information activity on click. Pending Intents can be given to other applications which serve as permission for the app to perform specified operation.

public class Widget extends AppWidgetProvider
{
    private Handler mHandler  = new Handler();
    RemoteViews views;
	AppWidgetManager appWidgetManager;
	ComponentName currentWidget;
	Context context;
	DateFormat format = SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT,Locale.getDefault());

	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
	{

		//Update Widget Using a a runnable and a handler to manage it.
		.
		// some code here.
		.
		mHandler.removeCallbacks(mUpdateTask);
       		mHandler.postDelayed(mUpdateTask, 100);

	} 

	final Runnable mUpdateTask = new Runnable()
	{
	   public void run()
	   {
		   Intent informationIntent = new Intent(context,info.class);
	       PendingIntent infoPendingIntent = PendingIntent.getActivity(context, 0, informationIntent, 0);
	       views.setOnClickPendingIntent(R.id.Widget, infoPendingIntent);
		   views.setTextViewText(R.id.widget_textview,format.format(new Date()));
		   appWidgetManager.updateAppWidget(currentWidget, views);
		   mHandler.postDelayed(mUpdateTask, 1000);

	   }
	};

Step 5: Create Information activity and xml file

This is a simple activity with a text view that is used to display some information on click of the widget. Creating a layout may be a piece of cake for you by now but the sample is there for your reference as always.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
			    android:layout_width="fill_parent"
			    android:layout_height="fill_parent"
			    android:background ="@android:color/white"
			    android:scrollbars="vertical">

	<TextView android:layout_width="fill_parent"
			  android:layout_margin="3dip"
			  android:textColor="@android:color/black"
			  android:layout_height="wrap_content"
			  android:text="@string/information" />

</RelativeLayout>

So here we go, with the help of a few simple steps, we have created our very own widget. Wasn’t that straightforward? I am sure you would be amused at the simplicity of the thing and yet its elegant beauty which is there for all to see.

As with everything, along with a dozen of advantages there are a few downsides to it , else how would we improvise? So a few things that you must keep in mind while you are involved in creating widgets are:

  • They can consume a lot of resources, battery life so you need to regularly kill open unused apps.
  • They take some real estate on screen, so you need alternate screens and launchers for some extra space.

So keep these in mind while making and embedding widgets on your home screen and you should have absolutely no problem. If you still get stuck while making your widget you can always use the entire source which is available for download or leave a comment and I would be pleased to answer it.

Vinay Ramkrishnan
Vinay Ramkrishnan– Team Member – Mobile CoE

, , , ,

03
Aug
This entry is part 3 of 3 in the series Mobile UI Design Pattern

The previous posts on User Interface tips and Dashboard design pattern gave you a fair idea on how to get going with your User Interface.

In this post, we shall look at the Action Bar design pattern in more detail which will enable you to better understand and execute Action Bars on your user interface.

Introduction:

As previously mentioned, action bar is a bar placed atop the screen that houses all the essential actions used in an application. It contains only those actions that are common to the entire application, and not activity specific ones. It is very commonly used in most applications, some even before it was introduced as a design pattern.

The Twitter Application for Android is a prime example. It has an action bar that provides actions like refresh, search, messages etc. The Facebook app is another common app that uses this pattern. Imagine if every app had an action bar, how useful and user friendly it would be. Navigation can also be added there. For now, this should suffice. Let us take a look at how do you actually go about creating it. Of the 3 patterns this is the easiest pattern to implement. So let us try and implement this step by step in the same manner as described in Dashboard Design pattern. Please refer -Xoriant Source Code for Android Dashboard UI Pattern

Take a look at the images below :

Follow these few simple steps to get going with your Action Bar:

Step 1: Create Action Bar Class

First of all, you need to create an abstract base class that houses all the common functionalities like the lifecycle method and the” onClick” handlers similar to the dashboard. In this, “onClick” handlers refer to actions that need to be triggered when the actions on the action bar are clicked. This should be pretty simple, especially after doing it for the dashboard. But as always the sample snippet is available for your reference.

public abstract class ActionBarAppActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
    }

    public void onSearch(View v)
    {
    	startActivity (new Intent(getApplicationContext(), SearchActivity.class));
    }

    public void onHome (View v)
    {
    	return2Home(this);
    }

    public void return2Home(Context context)
    {
        final Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity (intent);
    }
}

Step 2: Create Layout For Action Bar

You have got your base class ready. That means half the job is done. Now simply create the layout for the home screen along with the action bar. Remember the title bar will not be present in the application. It will be replaced by the action bar. The layout must include an icon for home, the title of the current view and other options to be displayed on the bar. Don’t include more than 3 options as it looks cluttered. Creating layouts by now won’t be a hurdle. All you need is a couple of image views and text views. The necessary icons/images may be stored in the resources and referred to in the usual way. With the hints I have given you the layout shouldn’t take long to make. Anyhow a sample snippet is always there at your disposal. Take a look at the sample above. Just to remind you; it is only a snippet not the entire code.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
			  android:orientation="horizontal"
			  android:layout_width = "fill_parent"
			  android:layout_height="wrap_content"
			  android:gravity="right"
			  android:layout_gravity="right">

			   <ImageButton style="@style/TitleBarOperation"
            			   android:src="@drawable/about_click"
            			   android:onClick="onAbout"
            			   android:layout_marginTop = "6dip"
            			   android:layout_marginBottom = "4dip"
            			   android:layout_marginLeft="5dip"
            			   android:background="@null"
            			   android:layout_marginRight="5dip"/>

			  <ImageView android:layout_width="1px"
			   android:layout_height="fill_parent"
			   android:background="@drawable/separator"
			   android:layout_marginLeft = "5dip"
			   android:layout_marginRight="5dip"
			   />

			  <ImageButton style="@style/TitleBarOperation"
            			   android:src="@drawable/search"
            			   android:layout_marginTop = "6dip"
            			   android:layout_marginBottom = "4dip"
            			   android:onClick="onSearch"
            			   android:background="@drawable/home_bg"
            			   android:layout_marginRight="5dip"/>
	</LinearLayout>

Step 3: Append Action Bar to all Activities and create layouts (Modify action bar in case of search)

Now all that remains is replicating the same layout of the home screen action bar across all the other activities. That is simple replication of the code. Also generate the layout for the remaining activities. In case of the search activity, only a slight modification will be needed to the action bar to include a search box as well. That is as simple as appending an edit text to the layout. Have a look at the code snippet below.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
			  android:orientation="horizontal"
			  android:layout_width = "wrap_content"
			  android:layout_height="wrap_content"
			  android:gravity="left|center_vertical"
			  android:layout_gravity="left">

			  <ImageButton style="@style/TitleBarOperation"
            			   android:src="@drawable/home_def"
            			   android:background="@drawable/home_bg"
            			   android:onClick="onHome"
            			   android:layout_marginTop = "5dip"
            			   android:layout_marginRight="5dip"
            			   android:paddingBottom="3dip"
            			   android:layout_marginLeft = "4dip"
            			   android:layout_marginBottom = "4dip"
            			   android:layout_gravity="center"/>

              <ImageView android:layout_width="1px"
			   android:layout_height="fill_parent"
			   android:background="@drawable/separator"
			   android:layout_marginRight="5dip"/>

              <TextView style="@style/TitleBarText"
              			android:id = "@+id/title_text"
              			android:text = "Action Bar Sample"
              			/>

              <ImageView android:layout_width="1px"
			   android:layout_height="fill_parent"
			   android:background="@drawable/separator"
			   android:layout_marginLeft="5dip"
			   />

              <EditText android:id="@+id/input_text"
              			android:layout_height="fill_parent"
              			android:layout_width="100dip"
              			android:layout_marginTop="2dip"
              			android:layout_gravity="center"
              			android:textSize="10sp"
              			android:text = "search here..."
              			android:layout_marginLeft="5dip"
              			android:layout_marginRight="5dip"/>

			<ImageView android:layout_width="1px"
			   android:layout_height="fill_parent"
			   android:background="@drawable/separator"
			   android:layout_marginLeft="2dip"/>

Step 4: Modifying styles.xml

With this, your Action Bar is ready. All that remains is adding a few lines of code to your styles.xml file. This style must be appended to the manifest as a theme in the application tag. Basically these lines specify that there will be no title bar in the application, and instead will be overlaid by our own custom action bar. See the sample code to understand.

<style name="Theme.D1" parent="android:style/Theme.Light">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

We have successfully implemented the Action Bar by following these 4 simple steps. Now you can create your very own action bar with actions of your choice. With this we have completed 2 of  the 3 design patterns. The third pattern will soon follow. Only if could imagine how attractive your UI would be if you were to use all 3 patterns in an app. Hopefully you have understood and enjoyed learning these patterns as much as I  am pleased to share them.

Source Code

Should you require full source code for Action Bar, please refer Xoriant-Source Code for Android Action Bar.Like always you can leave your comments here and I will look forward to answering them.

There will be the next blog on design patterns for Quick Actions soon. So watch out for the space to complete your User Interface with third and final design pattern!!

Vinay Ramkrishnan
Vinay Ramkrishnan– Team Member – Mobile CoE

, , , , , ,