2014-07-20 71 views
0

中持久我已閱讀here,首選項會自動保留。我試着按照說明操作,但複選框始終有其默認值。我的代碼去如下:首選項不會在android

1)我打開首屏菜單:

int id = item.getItemId(); 
if (id == R.id.action_settings) { 
      { 
      Intent myIntent = new Intent(this, PreferencesActivity.class); 
      startActivity(myIntent); 
      } 

2)首片段類,加載設置:

public class SettingsFragment extends PreferenceFragment { 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    addPreferencesFromResource(R.xml.preference_screen); 
} 

}

3)和活動,加載片段:

public class PreferencesActivity extends Activity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    getFragmentManager().beginTransaction() 
      .replace(android.R.id.content, new SettingsFragment()) 
      .commit(); 
} 
} 

偏好設置屏幕的xml:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > 
<CheckBoxPreference android:enabled="true" 
android:title="@string/ShowAdsTitle" 
android:summaryOn="@string/ShowAdsOnPreference" 
android:selectable="true" 
android:summaryOff="@string/ShowAdsOnPreference" 
android:key="@string/value_showads_preference"/> 
</PreferenceScreen> 

不知怎的,我的設置不是永久性的。 android:key是爲我的每個設置設置的。

在此先感謝!

+0

您是否也可以包含xml文件? – vandus

+0

@vandus爲片段添加了xml – Anton

+0

嘗試從'PreferenceActivity'中使用它,而不是使用其他'Activity'。 – CommonsWare

回答

1
android:key="value"/> 

試着將直接字符串安卓:從字符串鍵,而不是一個值作爲您將無法訪問已翻譯的鍵值

+0

也嘗試過,結果相同,對不起。 – Anton

+0

對不起,我的不好;那就像魅力一樣工作! – Anton

1

它爲我,所以我會形容我的步驟:

在MainActivity中的onCreate:

Intent myIntent = new Intent(this, PrefActivity.class); 
    startActivity(myIntent); 

這將打開Preferences活動。

public class PrefActivity extends Activity 
{ 
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 

    getFragmentManager().beginTransaction() 
      .replace(android.R.id.content, new SettingsFragment()) 
      .commit(); 
} 
} 

這將啓動SettingsFragment。

@TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SettingsFragment extends PreferenceFragment 
{ 
@Override public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    addPreferencesFromResource(R.xml.preference_screen); 
} 
} 

這是設置XML代碼:

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 
<CheckBoxPreference 
    android:enabled="true" 
    android:title="show ads" 
    android:summaryOn="show ads on" 
    android:selectable="true" 
    android:summaryOff="show ads on" 
    android:key="value"/> 
</PreferenceScreen> 

我不知道什麼樣的階級是Preferences.class但也可能是這個問題。不管怎麼說,這個代碼的工作,它很好地檢查,並取消選中的喜好,並保持它回去表格後,這種方式並把它:)

+0

噢,我在問題中間重構了代碼:(現在編輯它,首選項是PreferencesActivity。此外,沒有注意到我的代碼有任何重大變化。 – Anton

+0

您使用什麼樣的設備進行測試? API級別 – vandus

+0

preference_settings.xml位於res文件夾中的xml文件夾中 – vandus