我试图这样做,以便在按下我的小部件上的图像按钮时,它将改变文本视图的文本。此textviews数据是一个数组中的随机字符串(Something我已经有代码)。我开始看一下广播接收器,但我真的不知道为什么我的工作不起作用。任何帮助都非常感谢:)
小工具活动
public class Widget extends AppWidgetProvider {
private Random rgenerator = new Random();
private 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();
intent.setAction(TestReceiver.TEST_INTENT);
intent.setClassName(TestReceiver.class.getPackage().getName(), TestReceiver.class.getName());
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
// 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);
}
}
}
广播收发器:
package kevin.erica.box;
public class TestReceiver extends BroadcastReceiver {
private Random rgenerator = new Random();
private Random rgenerator2 = new Random();
private String [] myString1;
private String myStringRandom = myString1[rgenerator.nextInt(myString1.length)];
public static final String TEST_INTENT= "MyTestIntent";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "Test", Toast.LENGTH_SHORT);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context.getApplicationContext());
Toast.makeText(context, "Test", Toast.LENGTH_SHORT).show();
int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);
RemoteViews rViews = new RemoteViews(context.getPackageName(), R.layout.widgetlayout);
rViews.setTextViewText(R.id.widget1label, "someupdateddata");
appWidgetManager.updateAppWidget(appWidgetIds, rViews);
}
}
答案 0 :(得分:0)
如果ImageButton和TextView都在同一个布局中,则BroadcastReceiver可能有点过分。
您是否在活动中尝试过类似的内容:
final Widget w = (Widget)findViewById(R.id.yourWidgetId);
ImageButton button = (ImageButton) findViewById(R.id.yourImageButtonId);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
w.onUpdate();
}
}
http://developer.android.com/reference/android/view/View.OnClickListener.html