2016-07-16 1 views
1

통화 선택을위한 ListPreference에 대한 환경 설정 활동이 있습니다. 기본 설정의 기본값은 "CHF"입니다.앱을 처음 실행할 때 SharedPreferences 기본값이 바인딩되지 않습니다.

그러나 앱을 설치하고 처음 실행하면 환경 설정이 sharedPreferences 파일에 저장되지 않은 것처럼 작동합니다.

주 활동에 대한 textview는이 환경 설정의 값에 따라 다르므로 앱을 처음 실행하더라도 환경 설정이 필요합니다. 내 주요 활동에

는 onResume에서, 나는 다음과 같은 메서드를 호출 :

private void bindMassageViews() { 
    String currency = PreferenceManager.getDefaultSharedPreferences(getContext()) 
      .getString(getString(R.string.currency_preference_key), ""); 
    massageName.setText(mBuilder.getMassageName()); 
    priceContentTextview.setText(String.format(priceElement, 
      String.valueOf(mBuilder.getPrice()), currency)); 
} 

선호 자체입니다 다음

:

<ListPreference 
    android:defaultValue="@string/swiss_franc_symbol" 
    android:entries="@array/pref_currency_values" 
    android:entryValues="@array/pref_currency_values" 
    android:key="@string/currency_preference_key" 
    android:negativeButtonText="@null" 
    android:positiveButtonText="@null" 
    android:title="@string/pref_title_currency" /> 

그리고 내 취향 활동이있다 공용 클래스 SettingsActivity는 AppCompatPreferenceActivity를 확장합니다. {

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    addPreferencesFromResource(R.xml.pref_general); 
    bindPreferences(); 
    setupActionBar(); 
} 

/** 
* Set up the {@link android.app.ActionBar}, if the API is available. 
*/ 
private void setupActionBar() { 
    ActionBar actionBar = getSupportActionBar(); 
    if (actionBar != null) { 
     // Show the Up button in the action bar. 
     actionBar.setDisplayHomeAsUpEnabled(true); 
    } 
} 

@Override 
public boolean onMenuItemSelected(int featureId, MenuItem item) { 
    int id = item.getItemId(); 
    if (id == android.R.id.home) { 
     if (!super.onMenuItemSelected(featureId, item)) { 
      NavUtils.navigateUpFromSameTask(this); 
     } 
     return true; 
    } 
    return super.onMenuItemSelected(featureId, item); 
} 

/** 
* A preference value change listener that updates the preference's summary 
* to reflect its new value. 
*/ 
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() { 
    @Override 
    public boolean onPreferenceChange(Preference preference, Object value) { 
     String stringValue = value.toString(); 

     if (preference instanceof ListPreference) { 
      // For list preferences, look up the correct display value in 
      // the preference's 'entries' list. 
      ListPreference listPreference = (ListPreference) preference; 
      int index = listPreference.findIndexOfValue(stringValue); 

      // Set the summary to reflect the new value. 
      preference.setSummary(
        index >= 0 
          ? listPreference.getEntries()[index] 
          : null); 

     } else { 
      // For all other preferences, set the summary to the value's 
      // simple string representation. 
      preference.setSummary(stringValue); 
     } 
     return true; 
    } 
}; 

/** 
* Binds a preference's summary to its value. More specifically, when the 
* preference's value is changed, its summary (line of text below the 
* preference title) is updated to reflect the value. The summary is also 
* immediately updated upon calling this method. The exact display format is 
* dependent on the type of preference. 
* 
* @see #sBindPreferenceSummaryToValueListener 
*/ 
private static void bindPreferenceSummaryToValue(Preference preference) { 
    // Set the listener to watch for value changes. 
    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener); 

    // Trigger the listener immediately with the preference's 
    // current value. 
    sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, 
      PreferenceManager 
        .getDefaultSharedPreferences(preference.getContext()) 
        .getString(preference.getKey(), "")); 
} 


private void bindPreferences() { 
    bindPreferenceSummaryToValue(findPreference(getString(R.string.currency_preference_key))); 
} 
} 

처음으로 앱을 실행할 때 환경 설정의 기본값이 바인딩되도록하려면 어떻게해야합니까?

+0

시도를 변경하는 경우 참조 , false);'당신의'onCreate'에서 무엇이 바뀌는 지 확인하십시오 – Vucko

+0

완벽합니다. 도와 주셔서 감사합니다. –

+0

문제 없습니다. 답변으로 의견을 게시 한 후 답변을 수락 하시겠습니까? – Vucko

답변

1

문제를 해결 도움이 내 댓글을 복사 :

에 한번 당신의에서 onCreate에 PreferenceManager.setDefaultValues(this, R.xml.preference, false);를 추가하고 아무것도에게 (`이, R.xml.preference을 PreferenceManager.setDefaultValues를 추가

관련 문제