桌面组件App Widget是Android的实用功能,开发过程虽然不是很难,但是步骤不少,略有麻烦。为了方便以后再次使用的时候,快速上手,概括了下面的关键步骤。并且把项目打了包,方便以后的使用。新建一个Android项目,按已下三步就可以制作一个简单App Widget。
Step 1 创建AppWidgetProvider子类
public class SimpleWidget extends AppWidgetProvider{ @Override public void onUpdate(Context context,AppWidgetManager appWidgetManager, int[] appWidgetIds){ super.onUpdate(context, appWidgetManager, appWidgetIds); } }
Step 2 创建App Widget布局文件和设置文件
布局文件 res/layout/simple_widget.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" /> </LinearLayout>
设置文件 res/xml/simple_widget.xml
(initialLayout要和布局文件名匹配)
<?xml version="1.0" encoding="utf-8"?> <appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android" android:initialLayout="@layout/simple_widget" android:minWidth="72dp" android:minHeight="72dp" android:updatePeriodMillis="86400000" > </appwidget-provider>
Step 3 修改AndroidManifest.xml
在Application节点下增加下面的子节点:
<receiver android:name="SimpleWidget" > <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/simple_widget" /> </receiver>
全部保存,到这一步就可以开始Run了。演示截图:
最后给出,打包的项目源代码包,下载地址。