我正在构建一个显示文本视图的小部件,该文本视图可作为配置类中的编辑文本进行编辑。而且我刚刚实现了共享首选项,因此当用户第二次或第三次编辑小部件等时,已经输入的文本将出现在配置类的 edittext 字段中。
我猜它有效。好吧,在我实现 sharedpreferences 之前,小部件在配置后会更新得很好。但是现在,我编辑文本,按应用,但小部件没有更新,然后我再次编辑小部件,小部件更新为我之前应用到它的文本。所以我想你可以说,这是一个延迟更新。我希望我很清楚,这有点难以解释。
所以我做错了什么,我无法让它工作,非常感谢任何帮助。
代码:
public class WidgetConfig extends Activity implements OnClickListener {
AppWidgetManager awm;
int awID;
Context c;
EditText info;
Button b;
String note;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.widgetconfig);
c = WidgetConfig.this;
info = (EditText)findViewById(R.id.etwidgetconfig);
b = (Button)findViewById(R.id.bwidgetconfig);
loadPrefs();
b.setOnClickListener(this);
//Getting Info about the widget that launched this activity
Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null){
awID = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID );
}
awm = AppWidgetManager.getInstance(c);
}
private void loadPrefs(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
note = sp.getString("NOTE", "DEFAULT");
info.setText(note);
}
private void savePrefs(String key, String value){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value); // value to store
editor.commit();
}
public void onClick(View v) {
// TODO Auto-generated method stub
savePrefs("NOTE", info.getText().toString());
RemoteViews views = new RemoteViews(c.getPackageName(), R.layout.widget);
views.setTextViewText(R.id.tvConfigInput, note);
ComponentName thisWidget = new ComponentName(this, Widget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(this);
manager.updateAppWidget(thisWidget, views);
Intent in = new Intent(c, WidgetConfig.class);
PendingIntent pi = PendingIntent.getActivity(c, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.B_EditAgain, pi);
awm.updateAppWidget(awID, views);
Intent result = new Intent();
result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, awID);
setResult(RESULT_OK, result);
finish();
}
}