0

我有一个我一直无法弄清楚的问题。我有一个从保存在 SharedPreferences 中的 ArrayList 加载的微调器。我允许用户通过一个单独的类 startActivityForResult 中的 PreferenceActivity 修改微调器名称。它可以工作,但除非应用程序关闭然后重新打开,否则我无法让微调器使用新名称刷新自身。

当用户使用后退键关闭编辑名称窗口时,结果代码和 result_ok 信息将正确传回。这是我无法弄清楚的地方。我知道我需要使用 NotifyDataSetChanged 但我不知道该怎么做,因为修改是在一个单独的类中进行的,而不是在 OnItemSelectedListener 中,就像 StackOverflow 上的许多问题的答案建议刷新微调器数据一样。

这是我的微调器代码:

private ArrayAdapter<String> adapter1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        /* enable hardware acceleration on Android >= 3.0 */
        final int FLAG_HARDWARE_ACCELERATED = WindowManager.LayoutParams.class
                .getDeclaredField("FLAG_HARDWARE_ACCELERATED").getInt(null);
        getWindow().setFlags(FLAG_HARDWARE_ACCELERATED,
                FLAG_HARDWARE_ACCELERATED);
    } catch (Exception e) {
    }
    checkPreferences();
    setContentView(R.layout.main);
    this.findViewById(R.id.label_mode).setOnClickListener(this);
    this.findViewById(R.id.label_clear).setOnClickListener(this);
    this.findViewById(R.id.label_data).setOnClickListener(this);
    this.findViewById(R.id.label_wifi).setOnClickListener(this);
    this.findViewById(R.id.label_roam).setOnClickListener(this);
    this.findViewById(R.id.label_vpn).setOnClickListener(this);
    this.findViewById(R.id.label_invert).setOnClickListener(this);

    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(getApplicationContext());
    // create the spinner
    spinner = (Spinner) findViewById(R.id.spinner);

    // profile names for spinner
    final List<String> profilestring = new ArrayList<String>();
    profilestring.add(prefs.getString("default",
            getString(R.string.defaultprofile)));
    profilestring.add(prefs.getString("profile1",
            getString(R.string.profile1)));
    profilestring.add(prefs.getString("profile2",
            getString(R.string.profile2)));
    profilestring.add(prefs.getString("profile3",
            getString(R.string.profile3)));
    profilestring.add(prefs.getString("profile4",
            getString(R.string.profile4)));
    profilestring.add(prefs.getString("profile5",
            getString(R.string.profile5)));
    profileposition = profilestring
            .toArray(new String[profilestring.size()]);

    // adapter for spinner
    adapter1 = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_dropdown_item, profileposition);

    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter1);
    spinner.setSelection(prefs.getInt("itemPosition", 0));
    spinner.post(new Runnable() {
        public void run() {
            spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> parent,
                        View view, int position, long id) {
                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                    int index = parent.getSelectedItemPosition();
                    if (index == 0) {
                        editor.putInt("itemPosition", index);
                        editor.commit();
                        LoadDefaultProfile();
                    }
                    if (index == 1) {
                        editor.putInt("itemPosition", index);
                        editor.commit();
                        LoadProfile1();
                    }
                    if (index == 2) {
                        editor.putInt("itemPosition", index);
                        editor.commit();
                        LoadProfile2();
                    }
                    if (index == 3) {
                        editor.putInt("itemPosition", index);
                        editor.commit();
                        LoadProfile3();
                    }
                    if (index == 4) {
                        editor.putInt("itemPosition", index);
                        editor.commit();
                        LoadProfile4();
                    }
                    if (index == 5) {
                        editor.putInt("itemPosition", index);
                        editor.commit();
                        LoadProfile5();
                    }
                }

                public void onNothingSelected(AdapterView<?> parent) {
                    // do nothing
                }
            });
        }
    });

然后我设置我的选择并使用 spinner.post(New Runnable) 运行微调器。

我的偏好屏幕非常简单。

<?xml version="1.0" encoding="utf-8"?>

<EditTextPreference
    android:key="default"
    android:summary="Edit name for Default Profile"
    android:title="@string/defaultprofile" />

<EditTextPreference
    android:key="profile1"
    android:summary="Edit name for profile1"
    android:title="@string/profile1" />

<EditTextPreference
    android:key="profile2"
    android:summary="Edit name for profile2"
    android:title="@string/profile2" />

<EditTextPreference
    android:key="profile3"
    android:summary="Edit name for profile3"
    android:title="@string/profile3" />

<EditTextPreference
    android:key="profile4"
    android:summary="Edit name for profile4"
    android:title="@string/profile4" />

<EditTextPreference
    android:key="profile5"
    android:summary="Edit name for profile5"
    android:title="@string/profile5" />

编辑名称类

public class EditProfileNames extends PreferenceActivity implements
    OnSharedPreferenceChangeListener {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.layout.prefs);
    PreferenceManager.setDefaultValues(EditProfileNames.this,
            R.layout.prefs, false);

    for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
        initSummary(getPreferenceScreen().getPreference(i));
    }
}

@SuppressWarnings("deprecation")
@Override
protected void onResume() {
    super.onResume();
    // Set up a listener whenever a key changes
    getPreferenceScreen().getSharedPreferences()
            .registerOnSharedPreferenceChangeListener(this);
}

@SuppressWarnings("deprecation")
@Override
protected void onPause() {
    super.onPause();
    // Unregister the listener whenever a key changes
    getPreferenceScreen().getSharedPreferences()
            .unregisterOnSharedPreferenceChangeListener(this);
}

@SuppressWarnings("deprecation")
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
        String key) {
    updatePrefSummary(findPreference(key));
}

private void initSummary(Preference p) {
    if (p instanceof PreferenceCategory) {
        PreferenceCategory pCat = (PreferenceCategory) p;
        for (int i = 0; i < pCat.getPreferenceCount(); i++) {
            initSummary(pCat.getPreference(i));
        }
    } else {
        updatePrefSummary(p);
    }

}

private void updatePrefSummary(Preference p) {
    if (p instanceof ListPreference) {
        ListPreference listPref = (ListPreference) p;
        p.setSummary(listPref.getEntry());
    }
    if (p instanceof EditTextPreference) {
        EditTextPreference editTextPref = (EditTextPreference) p;
        p.setSummary(editTextPref.getText());
    }

}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK)) {
        resultOk();
    }
    return super.onKeyDown(keyCode, event);
}

/**
 * Set the activity result to RESULT_OK and terminate this activity.
 */
private void resultOk() {
    final Intent response = new Intent(Api.PREF_PROFILES);
    setResult(RESULT_OK, response);
    finish();
}

}

那么我该怎么做才能刷新微调器?我知道如果在 OnItemSelectedListener 中进行了更改,我可以做到这一点,但因为它是一个完全不同的类,所以我现在迷失了。

谢谢!

4

2 回答 2

2

听起来您正在将对数组的引用传递profileposition给另一个类,以便它可以向其中添加元素。您还需要传递adapter对该类的引用,以便它可以adapter.notifyDataSetChanged();在更新数组后调用。

编辑:现在我看到您为结果而启动的 Acitivty 正在更新数组,您只需调用adapter.notifyDataSetChanged();回调onActivityResult()即可。

于 2013-02-25T20:11:42.810 回答
0

更改内容后,调用notifyDataSetChanged适配器即可解决问题。

试试这个方法

 adapter.notifyDataSetChanged();
于 2013-02-25T19:52:04.797 回答