Android桌面小组件的命名空间

来源:互联网 发布:雄鹿米德尔顿2017数据 编辑:程序博客网 时间:2024/05/17 03:35

今天发现,如果命名空间设置不对,无法控制widget的控件:

public class ParentsAppWidgetProvider extends AppWidgetProvider {    @Override    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {        // For each widget that needs an update, get the text that we should display:        //   - Create a RemoteViews object for it        //   - Set the text in the RemoteViews object        //   - Tell the AppWidgetManager to show that views object for the widget.        final int N = appWidgetIds.length;        for (int i=0; i<N; i++) {            int appWidgetId = appWidgetIds[i];            // Construct the RemoteViews object.  It takes the package name (in our case, it's our            // package, but it needs this because on the other side it's the widget host inflating            // the layout from our package).            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.appwidget_provider);                        // change color.            //views.setTextColor(R.id.appwidget_text, 0xFFEEEEEE);            views.setTextViewText(R.id.appwidget_text, "changed");                        // Tell the widget manager            appWidgetManager.updateAppWidget(appWidgetId, views);        }    }}

这段代码是在启动时就将组件的text设为“changed”,但是死活无效。

发现是默认的命名空间设置有问题,默认的AndroidManifest.xml的命名空间是:com.winlin.parents,生成的类是com.winlin.parents.ParentsAppWidgetProvider,必须将前面的命名空间改为com.winlin才行。

即AndroidManifest.xml的配置应该是:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.winlin"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="5"        android:targetSdkVersion="5" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >                <receiver android:name="com.winlin.parents.ParentsAppWidgetProvider">            <meta-data android:name="android.appwidget.provider"                    android:resource="@xml/appwidget_provider" />            <intent-filter>                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />            </intent-filter>        </receiver>            </application></manifest>

如下图所示:


原创粉丝点击