通过使用反射,我调用从我的 XML 文件PreferenceManager.inflateFromResource(Context, int, PreferenceScreen)
创建一个。PreferenceScreen
字符串资源在单独的文件中分隔并以taskname_
这是膨胀的代码PreferenceScreen
,它应该放在一个PreferenceActivity
:
/**
* Inflates a {@link android.preference.PreferenceScreen PreferenceScreen} from the specified
* resource.<br>
* <br>
* The resource should come from {@code R.xml}
*
* @param resId The ID of the XML file
* @return The preference screen or null on failure.
*/
private PreferenceScreen inflatePreferenceScreenFromResource(int resId) {
try {
Class<PreferenceManager> cls = PreferenceManager.class;
Method method = cls.getDeclaredMethod("inflateFromResource", Context.class, int.class, PreferenceScreen.class);
return (PreferenceScreen) method.invoke(getPreferenceManager(), this, resId, null);
} catch(Exception e) {
Log.w(LOG_TAG, "Could not inflate preference screen from XML", e);
}
return null;
}
以下是如何使用它的示例:
package com.example;
import java.lang.reflect.Method;
import com.example.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.util.Log;
public class ExamplePreferenceActivity extends PreferenceActivity {
public static final String PREFERENCE_NAME = "ExamplePreferences";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Sets the preference name
PreferenceManager pm = getPreferenceManager();
pm.setSharedPreferencesName(PREFERENCE_NAME);
// Adds default values and the root preference screen
PreferenceManager.setDefaultValues(this, PREFERENCE_NAME, MODE_PRIVATE, R.xml.preferences_layout, false);
addPreferencesFromResource(R.xml.preferences_layout);
PreferenceScreen root = getPreferenceScreen();
// Includes R.xml.other_preferences_layout and adds it to the bottom of the root preference screen
PreferenceScreen otherPreferenceScreen = inflatePreferenceScreenFromResource(R.xml.other_preferences_layout);
root.addPreference(otherPreferenceScreen);
PreferenceManager.setDefaultValues(this, PREFERENCE_NAME, MODE_PRIVATE, R.xml.other_preferences_layout, false);
}
/**
* Inflates a {@link android.preference.PreferenceScreen PreferenceScreen} from the specified
* resource.<br>
* <br>
* The resource should come from {@code R.xml}
*
* @param resId The ID of the XML file
* @return The preference screen or null on failure.
*/
private PreferenceScreen inflatePreferenceScreenFromResource(int resId) {
try {
Class<PreferenceManager> cls = PreferenceManager.class;
Method method = cls.getDeclaredMethod("inflateFromResource", Context.class, int.class, PreferenceScreen.class);
return (PreferenceScreen) method.invoke(getPreferenceManager(), this, resId, null);
} catch(Exception e) {
Log.w(LOG_TAG, "Could not inflate preference screen from XML", e);
}
return null;
}
}
此示例将res/xml/preferences_layout.xml
用作根,然后添加res/xml/other_preferences_layout.xml
到根的底部。