0

我一直在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()在这种情况下如何正确工作。

4

0 回答 0