想要创建个SettingsFragment, 发现Android Studio有现成的:
class SettingsFragment : PreferenceFragmentCompat() {
companion object{
val TAG: String = SettingsFragment::class.java.simpleName
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.root_preferences, rootKey)
}
}
root_preferences.xml
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceCategory app:title="@string/messages_header">
<EditTextPreference
app:key="signature"
app:title="@string/signature_title"
app:icon="@drawable/icon"
app:defaultValue="60"
app:iconSpaceReserved="false"
app:useSimpleSummaryProvider="true" />
<ListPreference
app:defaultValue="reply"
app:entries="@array/reply_entries"
app:entryValues="@array/reply_values"
app:key="reply"
app:title="@string/reply_title"
app:useSimpleSummaryProvider="true" />
</PreferenceCategory>
<PreferenceCategory app:title="@string/sync_header">
<SwitchPreferenceCompat
app:key="sync"
app:title="@string/sync_title" />
<SwitchPreferenceCompat
app:dependency="sync"
app:key="attachment"
app:summaryOff="@string/attachment_summary_off"
app:summaryOn="@string/attachment_summary_on"
app:title="@string/attachment_title" />
</PreferenceCategory>
</PreferenceScreen>
array.xml
<resources>
<string-array name="reply_entries">
<item>Reply</item>
<item>Reply to all</item>
</string-array>
<string-array name="reply_values">
<item>reply</item>
<item>reply_all</item>
</string-array>
</resources>
效果:
点击响应
override fun onPreferenceTreeClick(preference: Preference?): Boolean {
val connectionMode: SwitchPreferenceCompat? = findPreference("connect")
connectionMode?.setOnPreferenceChangeListener{ _, newValue ->
if (newValue == true){
}else{
}
true
}
}
如果不是执行操作,只是存储数据到SharePreference里,无需去监听onPreferenceTreeClick和setOnPreferenceChangeListener, 系统会将数据存储到app所在的目录data/data/com.example.demo/shared_prefs/com.example.demo_preferences.xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<boolean name="attachment" value="true" />
<string name="signature">Not set</string>
<string name="reply">reply_all</string>
<boolean name="sync" value="true" />
</map>
链接:整理设置
Customize your settings
|