Android Learning Note: Home screen Widgets (1): About widgets

Source: Internet
Author: User
Tags home screen

What is home screen Widgets

The home screen widget, called a gadget or a Chinese gadget, is a view that is displayed on the home page and updates the views data through the background process.

Android is managed by Appwidgetmanager to manage the widgets of the system. After installing the APK, the widget's name, icon, and space are displayed in the widget list according to the widget definition, and in Android4.0, the grid is displayed, some OEMs redesign the UI, and the widget list is presented in a different way.

By long pressing one of the widgets in the widget list and dragging it to the home page, we are actually creating an instance of the widget on the home page (instance). Appwidgetmanager. There can be multiple instances, and different instances use Widgetid to differentiate them.

The widget defines two important Java classes, one of which is the Widget Configurator activity, which is initialized by Appwidgetmanager through intent when the widget instance is generated. Where action is named Android.appwidget.action.APPWIDGET_CONFIGURE, this Java class is optional, usually in this configuration data input and save, due to the small amount of data can be easily saved in the shared The preference. If we create two widget instances, this configuration activity will be called two times.

A Java class that manages the life cycle of the widget, including when dragging to the home page, when it needs to be updated, and when it is dragged into the garbage bin. It is an inheritance of Appwidgetprovider, essentially a broadcast receiver that triggers different callback functions, such as the widget data update interval (given in the widget definition), based on the broadcast information emitted by Appwidgetmanager. The generation and deletion of widget instances, the generation of the first widget instance, and the deletion of the last widget instance.

The widget's build on the page is generated by Appwidgetmanager based on the layout file we gave in the widget definition, not directly generated by our code. As a result, we are not able to manipulate the view in the widget directly in the activity, which needs to be submitted to Appwidgetmanager to process an instance through Remoteviews.

Small Example

We will explain in detail how to create a widget through a small example. A small example is a birthday reminder.

When the widget instance is generated, configure activity, enter the name and date of birth in the activity, press the Set button to save the data in preference, and close the activity.

Widget top view display widget_id: First name, the middle left shows the number of days from the next birthday, click on the right view to open a page, the following shows the date of birth.


Defining a broadcast sink

As mentioned earlier, the widget has two important Java classes, an optional activity for configuration, a broadcast receiver for managing the Wdiget life cycle, and a receiver receiving Appwidgetmanager broadcast messages to trigger various callback functions. We need to define these two Java classes in Androidmanifest.xml, and the class definitions for the broadcast receivers are given below.

<manifest. >
<application ... android:label= "Testwidget" ......> <!--Android:label is the widget name in the widget list--
...
<receiverAndroid:name= ". Birthdaywidgetprovider ">
<meta-data android:name= "Android.appwidget.provider" android:resource= "@xml/birthday_widget_provider"/ >
<intent-filter>
<action android:name= "Android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>

</receiver>
</application>
</manifest>

This class is inherited by the Android.appwidget.AppWidgetProvider, which is set by the Meta-data parameter.

Here to add meta-data knowledge, the most common is the use of key-value pairs, that is, <meta-data android:name= "xxx" android:value= "yyy"/>, in the component can be obtained this value, For example, in activity:

Activityinfo actinfo = Mcontext.getpackagemanager (). Getactivityinfo (Getcomponentname (), PackageManager.GET_META_ DATA);
String msg = actInfo.metaData.getString ("Activity_name");

In the service, it is serviceinfo, in application for ApplicationInfo, in receiver for Activityinfo, but with Getreceiverinfo, If the ComponentName parameter is required, it can be obtained using the new ComponentName (context, Mycomponent.class).

Let's look at the code for Android.appwidget.AppWidgetManager.java:

/**
* Sent when it was time to update your appwidget.
*
* This is sent in response to a new instance for this Appwidget provider have
* Been instantiated
, the requested {@link Appwidgetproviderinfo#updateperiodmillis update interval} having lapsed, O R the system booting.
* ......
*
* @see appwidgetprovider#onupdate appwidgetprovider.onupdate (context context, Appwidgetmanager Appwidgetmanager, int[ ] appwidgetids)
*/
public static final String action_appwidget_update = "Android.appwidget.action.APPWIDGET_UPDATE";

/**
* Field for the manifest meta-data tag.
*
* @see Appwidgetproviderinfo
*/
public static final String Meta_data_appwidget_provider = "Android.appwidget.provider";

In Meta-data, Android.appwidget.provider is the keyword that is specified for Android, which is used to define the file for the app Widget provider information in the corresponding resource, which is located under xml/. This example is Res/xml/birthday_widget_provider.xml, which defines the widget's parameters.

Android.appwdiget.action.APPWIDGET_UPDATE is one of the receivers listening to Appwidgetmanger broadcast messages, the other is listening to action_appwidget_enabled and so on messages, However, in receiver it is necessary to indicate that the action_appwidget_update is the system to recognize that the receiver is actually a widget in order to add the widget to the widget list. Other messages that need to be monitored need not be listed here.

definition of App widget provider

In Manifest.xml, the appwidget provider defined by Meta-data is xml/birthday_width_provider.xml and the contents are as follows.

<?xml version= "1.0" encoding= "Utf-8"?>
<Appwidget-provider Xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:minwidth= "150DP"
Android:minheight= "120DP"
Android:updateperiodmillis= "43200000"
Android:initiallayout= "@layout/birday_widget"
android:configure= "Cn.wei.flowingflying.testwidget.ConfigBirthDayWidgetActivity"
Android:previewimage= "@drawable/gift"
Android:resizemode= "Horizontal|vertical" >
</appwidget-provider>

In the widget list, the widget size is 3x2. In XML, we define a length of 150DP, a width of 120dp, in fact the widget in home screen occupy the space is calculated by the grid, each grid is 74DPX74DP, the system will be allocated to accommodate the grid. The general cell phone grid is 4x4 and the tablet is 8x7. In the "Pro Android" book gives a recommendation of 74 N Times minus 2DP (adaptation border), and on the Android developer site recommended the definition of min length width of 70*n-30, here is an example:

This example has a time interval of 12 hours (43200000ms). Android strongly recommends 1 days up to only a few times, not too much. Starting from Android2.0, the minimum value is 30 minutes. if we set it to 0, we don't automatically update, we can control when the update is done by the Alarmmanager class. as an experimental small example, can be changed to 1 hours, but cannot be set too short, for example 1 minutes, in the simulator experiment, if the time interval is too short will not be triggered.

Starting with SDK3.1, users can resize widgets, including horizontal,vertical and none, by pressing the widget. To be able to resize, require the layout parameter to be scalable, and note that if size changes there is no callback reminder. Concrete How resize not too clear.

Previewimage is the icon in the widget list, if not, the main icon defined in the utility manifest file. The display in the widget list is also called Preview.

Configure the definition of activity

Java class configbirthdaywidgetactivity, which is defined by Android:configure in Appwidget-provider, is an ordinary activity, The code snippet that needs to be described in Androidmanifest.xml and supports response to Appwidget_configure Action,androidmanifest.xml is as follows:

<activity android:name= ". Configbirthdaywidgetactivity "android:label=" Configuration Birthday gadget >
<intent-filter>
<action android:name= "Android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>

So far, we've done the widget definition, and even if we don't write any Java class code specifically, we can still package it and install it on the device. After installation, see our small example testwidget in the widget list.

The widget's appearance definition

Define the appearance of the widget in Appwidget-provider by Android:initiallayout. The corresponding layout/birday_widget.xml are as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
android:layout_width= "150DP"
android:layout_height= "120DP"
android:orientation= "Vertical"
android:background= "@drawable/box1" >
<textview android:id= "@+id/bd_name"
Android:layout_width= "Match_parent"
android:layout_height= "30DP"
android:text= "Anonymous"
android:background= "@drawable/box1"
android:gravity= "Center"/>
<linearlayout android:orientation= "Horizontal"
Android:layout_width= "Match_parent"
android:layout_height= "60DP" >
<textview android:id= "@+id/bd_days"
Android:layout_width= "Wrap_content"
android:layout_height= "Match_parent"
android:text= "0"
android:gravity= "Center"
Android:textsize= "30SP"
Android:layout_weight= "/>"
<textview android:id= "@+id/bd_buy"
Android:layout_width= "Wrap_content"
android:layout_height= "Match_parent"
Android:textsize= "20SP"
android:text= "Buy"
Android:layout_weight= "50"
Android:background= "#FF6633"
android:gravity= "Center"/>
</LinearLayout>
<textview android:id= "@+id/bd_date"
Android:layout_width= "Match_parent"
android:layout_height= "30DP"
android:text= "2000/1/1"
android:background= "@drawable/box1"
android:gravity= "Center"/> "
</LinearLayout>

Unlike activity, it is not possible to get the object of the view directly in the code and to control it, and it needs to be controlled indirectly by Appwidgetmanager with Remoteviews. Therefore, in the widget appearance definition, view needs to support remote view, including Framelayout, LinearLayout, Relativelayout, AnalogClock, Button, chronometer, ImageButton, ImageView, ProgressBar, TextView, Viewflipper, ListView, GridView, StackView, Adapterviewflipper.

Android gives widget design guideline, see http://developer.android.com/guide/practices/ui_guidelines/widget_design.html.

The perimeter contour can be defined by android:background= "@drawable/box1". The contents of Res/drawable/box1.xml are as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<shape xmlns:android= "Http://schemas.android.com/apk/res/android" >
<stroke android:width= "4DP" android:color= "#888888"/> <!--define Borders--
<padding android:left= "2DP" android:top= "2DP" android:right= "2DP" android:bottom= "2DP"/>
<corners android:radius= "4DP"/>
</shape>


Android Learning Note: Home screen Widgets (1): About widgets

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.