0
我想使包含textview的小工具在點擊小工具時將其文本更改爲隨機數。它給一個顯示小部件的問題。我有這樣的代碼:小工具點擊更改小工具的文本
public class WidgetConfig extends AppWidgetProvider{
public static String RandomClick = "RandomClick";
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
RemoteViews updateViews;
ComponentName watchWidget;
updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
watchWidget = new ComponentName(context, WidgetConfig.class);
updateViews.setOnClickPendingIntent(R.id.randomnumber,getPendingSelfIntent(context, RandomClick));
appWidgetManager.updateAppWidget(watchWidget,updateViews);
Random r = new Random();
int randomInt = r.nextInt(6);
String randomStringInt = String.valueOf(randomInt);
final int N = appWidgetIds.length;
for (int i=0;i<N;i++){
int appWidgetID = appWidgetIds[i];
RemoteViews v = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
v.setTextViewText(R.id.randomnumber, randomStringInt);
appWidgetManager.updateAppWidget(appWidgetID, v);
}
}
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(RandomClick)){
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
RemoteViews updateViews;
ComponentName watchWidget;
updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
watchWidget = new ComponentName(context, WidgetConfig.class);
Random r = new Random();
int randomInt = r.nextInt(6);
String randomStringInt = String.valueOf(randomInt);
updateViews.setTextViewText(R.id.randomnumber, randomStringInt);
appWidgetManager.updateAppWidget(watchWidget, updateViews);
}
super.onReceive(context, intent);
}
protected PendingIntent getPendingSelfIntent(Context context, String action){
Intent intent = new Intent(context, getClass());
intent.setAction(action);
return PendingIntent.getBroadcast(context, 0, intent, 0);
}
}
在這randomnumber只是TextView的在widget_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/backgroundshape"
android:layout_margin="8dp"
android:onClick="ClickRandom">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:minHeight="56dp"
android:minWidth="56dp"
android:gravity="center"
android:id="@+id/randomnumber"
android:textSize="24dp"/>
</LinearLayout>
幫助非常感謝。謝謝!
問題是什麼 –