我一直在App
处理PreferenceActivity
,我有一个ListPreference
用于排序ListView
,位于MainActivity
。我已经实现了OnSharedPreferenceChangeListener()
,但当我回到MainActivity
我有一个listView
时,有些时候ListView
消失,当我关闭我的应用时然后重新启动它ListView
在我的选择中排序,最后一次在PreferenceActivity
中选择,我的代码是:
protected SharedPreferences settings = null;
private OnSharedPreferenceChangeListener changeListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
// Make a Connection to Database... and open it...
source = new CandidateDataSource(MainActivity.this);
source.opend_db();
objects = source.getAllData();
// adapter = new CandidateAdapter(MainActivity.this, objects, true);
adapter = initializeList(settings.getString("sort_order",
CandidateOpenHelper.COL_NAME));
changeListener = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences arg0,
String arg1) {
// TODO Auto-generated method stub
String setPrefs = settings.getString("sort_order", "Not Found");
adapter = initializeList(setPrefs);
Log.e("PREFS REFS", "PREF IS " + setPrefs);
}
};
settings.registerOnSharedPreferenceChangeListener(changeListener);
UIHelper.listHelper(MainActivity.this, R.id.list_container, adapter,
null, null);
}
private CandidateAdapter initializeList(String sort_order) {
if (objects != null) {
objects.close();
}
objects = source.getAllData(sort_order);
return adapter = new CandidateAdapter(MainActivity.this, objects, true);
}
UIHelper.listHelper()
方法如下:
static public void listHelper(Activity activity, int id, CandidateAdapter adapter, OnItemClickListener itemClickListener, OnItemLongClickListener longClickListener){
ListView listView = (ListView) activity.findViewById(id);
listView.setAdapter(adapter);
listView.setOnItemClickListener(itemClickListener);
listView.setOnItemLongClickListener(longClickListener);
}
在这种情况下如何使OnSharedPreferenceChangeListener()
正常工作。