Java 定期更新文本视图背景
我试图插入一个处理程序,每x秒更新一次widget_textview背景,但我不知道该放什么和在哪里Java 定期更新文本视图背景,java,android,timer,widget,textview,Java,Android,Timer,Widget,Textview,我试图插入一个处理程序,每x秒更新一次widget_textview背景,但我不知道该放什么和在哪里 int i; if (i==1) { TextView myTxt = (TextView) findViewById(R.id.widget_textview); myTxt.setBackgroundResource(R.drawable.pic1); i++;
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);
}
}
将其放在HandleMessage方法上的处理程序类实现中。此方法被重写
public class MyHandler extends Hadnler(
onHandlerMessage(Message msg){
//your code you want to put
}
}
对不起,我不明白,介意给我解释一下细节吗?抱歉,im仍然是newhandler是一种用于更新UI的特殊线程;您可以通过handler.sendEmptyMessage发送消息来更新线程;这将调用onHandleMessage方法,您可以在其中放置背景更新代码。这是您遇到问题的第一个代码段。我希望你理解处理程序的机制。如果你仍然有疑问,你可以搜索处理程序是如何工作的。你可以很容易地决定把你的代码放在哪里。我的朋友非常欢迎你。如果你理解它背后的功能,请喜欢我的答案。