Sunday, May 12, 2013

Steps to create Andriod Widget

In this article will help us to create customized Widget.

1. Create a Layout for Widget
2. Create Widget Class
3. Adding the Widget Provider Info Metadata
4. Register the Widget in Androidmanifest.xml
5. Add the Widget in your homepage


Create a Layout for Widget
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@drawable/widget_bg">
    <Button android:text="Click" android:id="@+id/Button01"
        android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>

    <TextView android:id="@+id/text" android:layout_width="fill_parent"
        android:layout_height="fill_parent" android:text="@string/hello"
        android:gravity="center" android:textColor="@android:color/black" />
</LinearLayout>

Create Widget Class
public class Widget extends AppWidgetProvider {
    private SimpleDateFormat formatter = new SimpleDateFormat(
            "EEE, d MMM yyyy\nHH:mm:ss.SSS");

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
            int[] appWidgetIds) {
       
        String now = formatter.format(new Date());

        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);

        RemoteViews updateViews = new RemoteViews(context.getPackageName(),R.layout.main);
        updateViews.setTextViewText(R.id.text, now);
        appWidgetManager.updateAppWidget(appWidgetIds, updateViews);

       
        RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.main);
        views.setOnClickPendingIntent(R.id.Button01, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetIds, views);

        super.onUpdate(context, appWidgetManager, appWidgetIds);

    }
}

Adding the Widget Provider Info Metadata

    <?xml version="1.0" encoding="utf-8"?>
    <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
        android:minWidth="166dip" android:minHeight="72dip" android:updatePeriodMillis="60000" android:initialLayout="@layout/main" />


Register the Widget in Androidmanifest.xml

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

Add the Widget in your homepage
    Click Menu -> Add -> Widget -> YOUR WIDGET