我试图用图像按钮和文本视图构建一个小部件,当我的图像按钮被按下时,我希望它将文本更改为数组中的随机字符串。我有我认为可行的方法,但它不会更新我的文本,也不知道为什么。我的 imagebutton 称为 imagewidgeterica,我的 textview 称为 widget1label。
这是我的代码:
package kevin.erica.box;
import java.util.Arrays;
import java.util.Random;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RemoteViews;
import android.widget.TextView;
public class Widget extends AppWidgetProvider {
private static final Random rgenerator = new Random();
private static final Random rgenerator2 = new Random();
private String[] myString1;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Resources res = context.getResources();
myString1 = res.getStringArray(R.array.myArray);
final int N = appWidgetIds.length;
Log.i("ExampleWidget", "Updating widgets " + Arrays.asList(appWidgetIds));
// Perform this loop procedure for each App Widget that belongs to this
// provider
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
// Create an Intent to launch ExampleActivity
Intent intent = new Intent(context, Widget.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
// Get the layout for the App Widget and attach an on-click listener
// to the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widgetlayout);
views.setOnClickPendingIntent(R.id.imagewidgeterica, pendingIntent);
// To update a label
views.setTextViewText((R.id.widget1label, myString1[rgenerator.nextInt(myString1.length)]);
// Tell the AppWidgetManager to perform an update on the current app
// widget
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
}
显现:
<receiver android:name=".Widget" android:label="Erica's Box">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<meta-data android:name="android.appwidget.provider" android:resource="@xml/erica_info" />
</receiver>