安卓小部件上的TextView.setText不起作用

3

我有一个非常简单的AppWidgetProvider用于测试小部件:

public class Test extends AppWidgetProvider {

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.test_layout);
        views.setTextViewText(R.id.TextView01, "Test message");
    }

}

测试布局如下所示:

<LinearLayout 
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
        android:id="@+id/TextView01" 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    </TextView>
</LinearLayout>

问题在于小部件出现在模拟器屏幕上,但没有任何文本。我确定我搞错了什么,但我找不到是什么...

1个回答

9

您忘记设置RemoteViews的使用。您的AppWidgetProvider代码应该是这样的:


public class Test extends AppWidgetProvider {
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){ super.onUpdate(context, appWidgetManager, appWidgetIds); RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.test_layout); views.setTextViewText(R.id.TextView01, "测试消息"); appWidgetManager.updateAppWidget(appWidgetIds, views); }
}

谢谢。我也犯了同样的错误。另外,在你的 onUpdate 方法中,你需要把 super.onUpdate(context, appWidgetManager, appWidgetIds); 放回第一行。 - yancyn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接