我正在编写“时间表应用”,它必须在今天的课程中显示为应用小部件中的listView。
所有数据(所有工作日)都存储在一个名为Data的文件中。应用程序小部件获取Data onCreate,然后填充它们以获取当天的数据。
但是当我向数据文件添加新课程时该怎么办?有没有办法重新创建app小部件,以获取更新的数据?
抱歉我的英语不好。谢谢你的回答
我的RemoteViewsFactory的代码如下:
public class ViewsFactory implements RemoteViewsService.RemoteViewsFactory {
List data;
int day;
private Context ctxt;
private int appWidgetId;
public ViewsFactory(Context ctxt, Intent intent) {
this.ctxt=ctxt;
appWidgetId=intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
@Override
public void onCreate() {
File file = new File(ctxt.getFilesDir(),"default.txt");
if(file.exists()){
ReadFile readFile = new ReadFile(file);
data = readFile.read();
Collections.sort(data, new AlphanumComparator());
}
}
@Override
public void onDestroy() {
// no-op
}
@Override
public int getCount() {
return data.size();
}
@Override
public RemoteViews getViewAt(int i) {
RemoteViews row=new RemoteViews(ctxt.getPackageName(), R.layout.row2);
SharedPreferences settings = ctxt.getSharedPreferences("UserPref", 0);
if(i==0) { //get week day only once
Calendar calendar = Calendar.getInstance();
day = calendar.get(calendar.DAY_OF_WEEK);
if (day == 1) day = 7;
else day -= 1;
SharedPreferences.Editor editor = settings.edit();
editor.putInt("currentDay", (day - 1)); //save current day for heading
editor.commit();
}
if(settings.getString("Days","").contains(Integer.toString(day-1))&&
data.get(i).toString().startsWith(Integer.toString(day))&&
(data.get(i).toString().endsWith(settings.getString("OddEven",""))||data.get(i).toString().endsWith(",X1X2"))) { //filtering
String[] dataLine = data.get(i).toString().split(",");
row.setTextViewText(R.id.text1, dataLine[1]); //set texsts
row.setTextViewText(R.id.text3, dataLine[2]);
row.setTextViewText(R.id.text4, dataLine[4]);
row.setTextViewText(R.id.text5, dataLine[6]);
}
return(row);
}
@Override
public RemoteViews getLoadingView() {
return(null);
}
@Override
public int getViewTypeCount() {
return(1);
}
@Override
public long getItemId(int position) {
return(position);
}
@Override
public boolean hasStableIds() {
return(true);
}
@Override
public void onDataSetChanged() {
// no-op
}
}
答案 0 :(得分:0)
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
int appWidgetIds[] = appWidgetManager.getAppWidgetIds(
new ComponentName(context, YourWidgetProviderClass.class));
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.<YourListView>);
添加新记录时添加这些行