android - widget帮助

时间:2011-04-29 11:17:58

标签: android widget

我最近尝试制作一个显示当前电池状态的电池小部件。

我输入了源代码:

java文件:

package cam.widget.batterywiz;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.RemoteViews;

public class batwiz extends AppWidgetProvider {
    /** Called when the activity is first created. */
    @Override
    public void onUpdate (Context c, AppWidgetManager awm, int[] id) {
        c.startService(new Intent (c, UpdateService.class));
    }

    public static class UpdateService extends Service {
        public void onStart (Intent intent, int startId) {
            RemoteViews rv = new RemoteViews (getPackageName(), R.layout.bat);
            rv.setTextViewText(R.id.battery, "80%");
            ComponentName thiswidget = new ComponentName (this, batwiz.class);
            AppWidgetManager m = AppWidgetManager.getInstance(this);
            m.updateAppWidget(thiswidget, rv);
        }


        @Override
        public IBinder onBind(Intent intent) {
            // TODO Auto-generated method stub
            return null;
        }

    }
}

bat2.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/widget"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >

    <ImageView
        android:id="@+id/battery"
        android:src="@drawable/battery_icon"
        android:cropToPadding="true"
    >
    </ImageView>
</LinearLayout>

android manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="cam.widget.batterywiz"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <receiver android:name=".batwiz">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                       android:resource="@layout/bat" />
        </receiver>

    </application>
    <uses-sdk android:minSdkVersion="4" />

</manifest> 
你们可以试着找出我的错误吗? 因为在我的模拟器中它说“问题加载小部件”
THX的帮助..

1 个答案:

答案 0 :(得分:2)

问题出在您的清单文件中,它显示为@xml/bat

您的提供商信息应位于/res/xml文件夹中。

此外,您需要将RemoteViews创建更改为 RemoteViews rv = new RemoteViews (getPackageName(), R.layout.bat2);

ImageViews没有SetText方法。

编辑:

更改

RemoteViews rv = new RemoteViews (getPackageName(), R.layout.bat2);

android:resource="@xml/bat" />

(并将bat.xmllayout/移至xml/

rv.setTextViewText(R.id.battery, "80%");

这不起作用,ImageView不是TextView的孩子,因此它没有SetText方法。