2013-04-06 20 views
1

我在我的android應用程序中有一個PreferenceActivity,用於顯示設置屏幕。我想在其中有一個「MultiSelectListPreference」,但我遇到了一個問題,它不適用於API的pre-API11版本,因爲它已在API11中引入。 沒問題,在那裏,我有兩個xml佈局,其中一個帶有位於res/xml-v11中的「MultiSelectListPreference」,另一個帶有「Preference」駐留在res/xml中,我使用自定義對話框處理。根據SDK版本動態加載首選項

在水庫中的XML文件/ XML-V11看起來是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 
<Preference android:key="time" 
      android:persistent="false" 
      android:title="@string/time" /> 
<MultiSelectListPreference android:key="days_multi" 
          android:persistent="false" 
          android:title="@string/days" /> 
<ListPreference android:key="action" 
       android:persistent="false" 
       android:title="@string/action" /> 
</PreferenceScreen> 

而且一個在res/XML看起來是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 
<Preference android:key="time" 
      android:persistent="false" 
      android:title="@string/time" /> 
<Preference android:key="days_dialog" 
      android:persistent="false" 
      android:title="@string/days" /> 
<ListPreference android:key="action" 
       android:persistent="false" 
       android:title="@string/action" /> 
</PreferenceScreen> 

正如你所看到的,只有differense是列表中的第二個元素,其餘部分完全相同。有沒有更好的方法來處理這個問題,以便在一個文件中重複使用相同的代碼並根據Android版本動態引用剩餘的部分?理想的解決方案將是這個樣子:

<?xml version="1.0" encoding="utf-8"?> 
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 
<Preference android:key="time" 
      android:persistent="false" 
      android:title="@string/time" /> 
<Preference source="days.xml" /> 
<ListPreference android:key="action" 
       android:persistent="false" 
       android:title="@string/action" /> 
</PreferenceScreen> 

雖然我也有文件下RES/XML-V11和包含一塊是不同的RE/XML稱爲days.xml。

我在文檔中找不到與StackOverflow相關的任何內容。 Android提供了一種方法來做到這一點?或者也許有其他方法來分解通用代碼?

回答

1

想到的是使用類似<include/>標籤的東西。看起來你不能在偏好xmls中使用它,但是你可以在部分中創建你的偏好。所以,你需要在你的PreferencesActivity像這樣(其中R.xml.prefs_days是2個版本的版本特定的文件)創建的首選項:

addPreferencesFromResource(R.xml.prefs_time); 
addPreferencesFromResource(R.xml.prefs_days); 
addPreferencesFromResource(R.xml.prefs_action); 

Nested preferences.xml

+0

這正是我發佈這個問題後認爲正確的做法: )它確實對我有用。但是我可以在這裏看到sevaral的缺點,即如果它們分佈在多個文件中,如何將多個首選項包裝到PreferenceCategory中? – 2013-04-06 02:59:47

+0

好的問題,這是超出我的領域的知識領域,因爲我沒有以這種更先進的方式使用它們。 – 2013-04-06 03:03:41