android TextView.setText不适用于简单的小部件

Bru*_*sso 3 android android-widget android-emulator

我有一个非常简单的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");
    }

}
Run Code Online (Sandbox Code Playgroud)

test_layout如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

问题是小部件出现在模拟器屏幕中但没有任何文本.我敢肯定,这是我弄乱的东西,但我找不到它是什么......

Rau*_*nak 9

您忘记设置要使用的RemoteView.您的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, "Test message");
        appWidgetManager.updateAppWidget(appWidgetIds, views);
    }

}