Android微调器刷新而不使用OnItemSelectedListener

时间:2013-02-25 19:47:35

标签: android spinner sharedpreferences

我有一个我无法弄清楚的问题。我有一个spinner从一个保存在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" />

EditNames类

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中进行了更改,我可以做到这一点,但因为它是一个完全不同的类,它使得我现在丢失了更改。

谢谢!

2 个答案:

答案 0 :(得分:1)

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

编辑:现在,我发现您已经开始为结果启动的Acitivty正在更新数组,您可以在adapter.notifyDataSetChanged();回调中调用onActivityResult()

答案 1 :(得分:0)

更改内容后,请在适配器上调用notifyDataSetChanged,这将解决问题。

试试这种方式

 adapter.notifyDataSetChanged();