我试图插入一个处理程序来每隔x秒更新一次widget_textview背景,但我不知道放置什么和放置
int i;
if (i==1) {
TextView myTxt = (TextView) findViewById(R.id.widget_textview);
myTxt.setBackgroundResource(R.drawable.pic1);
i++;
}else if(i==2) {
TextView myTxt = (TextView) findViewById(R.id.widget_textview);
myTxt.setBackgroundResource(R.drawable.pic2);
i++;
}else if(i==3) {
TextView myTxt = (TextView) findViewById(R.id.widget_textview);
myTxt.setBackgroundResource(R.drawable.pic1);
i=2;
}else {
i++;
}
我无法将它放在任何地方,无论我在哪里放置此代码我都会在textview中出错
这是我的代码
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.widget.RemoteViews;
import android.widget.TextView;
public class Widget extends AppWidgetProvider {
private Handler handler = new Handler();
RemoteViews views;
AppWidgetManager appWidgetManager;
ComponentName currentWidget;
Context context;
DateFormat format = new SimpleDateFormat("HH:mm");
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
this.context = context;
this.appWidgetManager = appWidgetManager;
views = new RemoteViews(context.getPackageName(), R.layout.widget);
currentWidget = new ComponentName(context, Widget.class);
handler.removeCallbacks(UpdateWidget);
handler.postDelayed(UpdateWidget, 100);
}
final Runnable UpdateWidget = new Runnable() {
public void run() {
Intent informationIntent = new Intent(context, MainActivity.class);
PendingIntent infoPendingIntent = PendingIntent.getActivity(
context, 0, informationIntent, 0);
views.setOnClickPendingIntent(R.id.Widget, infoPendingIntent);
views.setTextViewText(R.id.widget_textview,
"" + format.format(new Date()));
appWidgetManager.updateAppWidget(currentWidget, views);
handler.postDelayed(UpdateWidget, 1000);
}
};
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
handler.removeCallbacks(UpdateWidget);
}
}
答案 0 :(得分:-1)
将它放在你的处理程序类实现onHandleMessage()方法中。这个方法被覆盖。
public class MyHandler extends Hadnler(
onHandlerMessage(Message msg){
//your code you want to put
}
}