因为PreferenceActivity加载的layout是以PreferenceScreen为底的,所以没办法在layout里面直接添加TextView之类的控件。
此时可以把PreferenceScreen当做一个listview,放在另一个layout中:
1. PreferenceScreen的layout,可以在其中添加一些类似CheckboxPreference
preference_screen_layout.xml
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:title="Change available services">
<SwitchPreference
android:key="key_screen_always_on"
android:title="@string/screen_always_on_title"
/>
<SwitchPreference
android:key="sensors_enable"
android:title="@string/enable_sensors_title"
/>
</PreferenceScreen>
2. 新加的layout,listview的ID用android内置的
add_textview_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/service_status_textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="20dp" /> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
3. PreferenceActivity中使用两个layout:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.layout.preference_screen_layout); setContentView(R.layout.add_textview_layout); pScreen = getPreferenceScreen(); mTextView = (TextView) findViewById(R.id.service_status_textView); mContext = this.getApplicationContext(); }
pScreen可以在后面来管理activity中的preference,mTextView可以用来更新text。
4. 另外,动态添加的CheckboxPreference需要update才能设置checked/unchecked。
private void addCheckboxPreference() { CheckBoxPreference checkPreference = new CheckBoxPreference(mContext); otherServicePreference.setTitle(title); otherServicePreference.setIcon(icon); otherServicePreference.setKey(mKey); otherServicePreference.setPersistent(true); otherServicePreference.setDefaultValue(false); pScreen.addPreference(checkPreference); updatePreferenceStatus(); }
private void updatePreferenceStatus() { PreferenceScreen screen = getPreferenceScreen(); final int preferenceCount = screen.getPreferenceCount(); Log.i(TAG,"preferenceCount = "+preferenceCount); for (int i = 0; i < preferenceCount; i++) { Preference preference = screen.getPreference(i); mServicePreference = (CheckBoxPreference) findPreference(preference.getKey()); mServicePreference.setChecked(true); } }