1 page.title=Thit t 2 page.tags=preference,preferenceactivity,preferencefragment 3 4 @jd:body 5 6 7 <div id="qv-wrapper"> 8 <div id="qv"> 9 10 <h2>Trong ti liu ny</h2> 11 <ol> 12 <li><a href="#Overview">Tng quan</a> 13 <ol> 14 <li><a href="#SettingTypes">Ty chn</a></li> 15 </ol> 16 </li> 17 <li><a href="#DefiningPrefs">nh ngha Ty chn trong XML</a> 18 <ol> 19 <li><a href="#Groups">To nhm thit t</a></li> 20 <li><a href="#Intents">S dng nh</a></li> 21 </ol> 22 </li> 23 <li><a href="#Activity">To mt Hot ng Ty chn</a></li> 24 <li><a href="#Fragment">S dng Phn on Ty chn</a></li> 25 <li><a href="#Defaults">Thit t Gi tr Mc nh</a></li> 26 <li><a href="#PreferenceHeaders">S dng Tiu Ty chn</a> 27 <ol> 28 <li><a href="#CreateHeaders">To tp tiu </a></li> 29 <li><a href="#DisplayHeaders">Hin th tiu </a></li> 30 <li><a href="#BackCompatHeaders">H tr cc phin bn c hn vi tiu ty chn</a></li> 31 </ol> 32 </li> 33 <li><a href="#ReadingPrefs">c Ty chn</a> 34 <ol> 35 <li><a href="#Listening">Theo di thay i ty chn</a></li> 36 </ol> 37 </li> 38 <li><a href="#NetworkUsage">Qun l S dng Mng</a></li> 39 <li><a href="#Custom">Xy dng mt Thit t Ty chnh</a> 40 <ol> 41 <li><a href="#CustomSelected">Quy nh mt giao din ngi dng</a></li> 42 <li><a href="#CustomSave">Lu gi tr ca thit t</a></li> 43 <li><a href="#CustomInitialize">Khi to gi tr hin ti</a></li> 44 <li><a href="#CustomDefault">Cung cp mt gi tr mc nh</a></li> 45 <li><a href="#CustomSaveState">Lu v khi phc trng thi ca Ty chn</a></li> 46 </ol> 47 </li> 48 </ol> 49 50 <h2>Lp kha</h2> 51 <ol> 52 <li>{@link android.preference.Preference}</li> 53 <li>{@link android.preference.PreferenceActivity}</li> 54 <li>{@link android.preference.PreferenceFragment}</li> 55 </ol> 56 57 58 <h2>Xem thm</h2> 59 <ol> 60 <li><a href="{@docRoot}design/patterns/settings.html">Hng dn thit k Thit t</a></li> 61 </ol> 62 </div> 63 </div> 64 65 66 67 68 <p>ng dng thng bao gm nhng thit t cho php ngi dng sa i cc tnh nng v hnh vi ca ng dng. V 69 d, mt s ng dng cho php ngi dng quy nh xem thng bo c c kch hot hay khng hoc quy nh tn sut 70 ng dng s ng b d liu vi m my.</p> 71 72 <p>Nu mun cung cp thit t cho ng dng ca mnh, bn nn s dng 73 cc API {@link android.preference.Preference} ca Android xy dng mt giao din ph hp vi 74 tri nghim ngi dng trong cc ng dng Android khc (bao gm thit t h thng). Ti liu ny m t 75 cch xy dng thit t ng dng ca bn bng cch s dng cc API {@link android.preference.Preference}.</p> 76 77 <div class="note design"> 78 <p><strong>Thit k Thit t</strong></p> 79 <p> bit thng tin v cch thit k thit t ca bn, hy c hng dn thit k <a href="{@docRoot}design/patterns/settings.html">Thit t</a>.</p> 80 </div> 81 82 83 <img src="{@docRoot}images/ui/settings/settings.png" alt="" width="435" /> 84 <p class="img-caption"><strong>Hnh 1.</strong> nh chp mn hnh t thit t ca ng dng 85 Messaging trn Android. Chn mt mc c nh ngha bi mt {@link android.preference.Preference} 86 s m ra mt giao din thay i thit t.</p> 87 88 89 90 91 <h2 id="Overview">Tng quan</h2> 92 93 <p>Thay v s dng cc i tng {@link android.view.View} xy dng giao din ngi dng, thit t c 94 xy dng bng cch s dng cc lp con khc nhau ca lp {@link android.preference.Preference} m bn 95 khai bo trong mt tp XML.</p> 96 97 <p>i tng {@link android.preference.Preference} l mt khi dng cho mt thit t 98 n l. Mi {@link android.preference.Preference} xut hin nh mt mc trong mt danh sch v cung cp 99 UI ph hp ngi dng sa i thit t. V d, mt {@link 100 android.preference.CheckBoxPreference} to mt mc danh sch hin th mt hp kim, v mt {@link 101 android.preference.ListPreference} to mt mc m ra mt hp thoi vi danh sch la chn.</p> 102 103 <p>Mi {@link android.preference.Preference} m bn thm c mt cp kha-gi tr tng ng m 104 h thng s dng lu thit t trong mt tp {@link android.content.SharedPreferences} 105 mc nh cho thit t ca ng dng ca bn. Khi ngi dng thay i mt thit t, h thng s cp nht gi tr 106 tng ng trong tp {@link android.content.SharedPreferences} cho bn. Ln duy nht m bn nn 107 trc tip tng tc vi tp {@link android.content.SharedPreferences} c lin kt l khi bn 108 cn c gi tr xc nh xem hnh vi ng dng ca mnh c c da trn thit t ca ngi dng khng.</p> 109 110 <p>Gi tr c lu trong {@link android.content.SharedPreferences} cho tng thit t c th l mt trong cc kiu d liu 111 sau:</p> 112 113 <ul> 114 <li>Boolean</li> 115 <li>Float</li> 116 <li>Int</li> 117 <li>Long</li> 118 <li>String</li> 119 <li>String {@link java.util.Set}</li> 120 </ul> 121 122 <p>V thit t ca ng dng ca bn c xy dng bng cch s dng cc i tng {@link android.preference.Preference} 123 thay v i tng 124 {@link android.view.View}, bn nn s dng mt lp con {@link android.app.Activity} hoc 125 {@link android.app.Fragment} chuyn dng hin th thit t danh sch:</p> 126 127 <ul> 128 <li>Nu ng dng ca bn h tr cc phin bn Android c hn 3.0 (API mc 10 v thp hn), bn phi 129 xy dng hot ng nh mt phn m rng ca lp {@link android.preference.PreferenceActivity}.</li> 130 <li>Trn phin bn Android 3.0 tr ln, thay vo , bn nn s dng mt {@link android.app.Activity} 131 truyn thng ni lu gi {@link android.preference.PreferenceFragment} hin th thit t ng dng ca bn. 132 Tuy nhin, bn cng c th s dng {@link android.preference.PreferenceActivity} to mt b tr hai bng 133 cho mn hnh ln khi bn c nhiu nhm thit t.</li> 134 </ul> 135 136 <p>Cch thit t {@link android.preference.PreferenceActivity} ca bn v cc thc th ca {@link 137 android.preference.PreferenceFragment} c trnh by trong cc phn v <a href="#Activity">To mt Hot ng Ty chn</a> v <a href="#Fragment">S dng 138 Phn on Ty chn</a>.</p> 139 140 141 <h3 id="SettingTypes">Ty chn</h3> 142 143 <p>Mi thit t cho ng dng ca bn u c biu din bi mt lp con c th ca lp {@link 144 android.preference.Preference}. Mi lp con li bao gm mt tp hp cc tnh cht ct li cho php bn 145 quy nh nhng th nh tiu cho thit t v gi tr mc nh. Mi lp con cng cung cp 146 cc tnh cht v giao din ngi dng chuyn dng ca chnh n. V d, hnh 1 mnh ha mt nh chp mn hnh t thit t ca ng dng 147 Messaging. Mi mc danh sch trong mn hnh thit t c h tr bi mt i tng {@link 148 android.preference.Preference} khc nhau.</p> 149 150 <p>Sau y l mt s ty chn ph bin nht:</p> 151 152 <dl> 153 <dt>{@link android.preference.CheckBoxPreference}</dt> 154 <dd>Hin th mt mc km mt hp kim cho thit t hoc c kch hot hoc b v hiu ha. Gi tr 155 c lu l mt boolean (<code>true</code> nu n c chn).</dd> 156 157 <dt>{@link android.preference.ListPreference}</dt> 158 <dd>M mt hp thoi km danh sch nt chn mt. Gi tr c lu 159 c th l bt k loi gi tr c h tr no (lit k bn trn).</dd> 160 161 <dt>{@link android.preference.EditTextPreference}</dt> 162 <dd>M mt hp thoi km mt widget {@link android.widget.EditText}. Gi tr c lu l mt {@link 163 java.lang.String}.</dd> 164 </dl> 165 166 <p>Xem lp {@link android.preference.Preference} bit danh sch tt c cc lp con khc v tnh cht 167 tng ng ca chng.</p> 168 169 <p>D nhin, cc lp tch hp khng p ng mi nhu cu v ng dng ca bn c th yu cu 170 lp con chuyn dng hn. V d, nn tng ny hin cha cung cp mt lp {@link 171 android.preference.Preference} cho vic chn mt s hay ngy. V th, bn c th cn phi nh ngha 172 lp con {@link android.preference.Preference} ca chnh mnh. c tr gip khi lm vy, hy xem phn v <a href="#Custom">Xy dng Thit t Ty chnh</a>.</p> 173 174 175 176 <h2 id="DefiningPrefs">nh ngha Ty chn trong XML</h2> 177 178 <p>Mc d bn c th khi to cc i tng {@link android.preference.Preference} mi vo thi gian chy, bn 179 nn nh ngha danh sch cc thit t ca mnh trong XML km mt phn cp ca cc i tng {@link android.preference.Preference} 180 . Vic s dng mt tp XML nh ngha b su tp thit t ca bn s c u tin v tp 181 cung cp mt cu trc d c, cp nht n gin. Bn cnh , cc thit t ng dng ca bn thng c 182 xc nh trc, mc d bn vn c th sa i b su tp vo thi gian chy.</p> 183 184 <p>Mi lp con {@link android.preference.Preference} c th c khai bo bng mt phn t XML m 185 khp vi tn lp , chng hn nh {@code <CheckBoxPreference>}.</p> 186 187 <p>Bn phi lu tp XML trong th mc {@code res/xml/}. Mc d bn c th t tn tp l 188 bt c th g mnh mun, n thng c t tn l{@code preferences.xml}. Bn thng ch cn mt tp, 189 bi cc nhnh trong phn cp (m m danh sch thit t ca ring chng) s c khai bo bng cch s dng cc thc th 190 lng nhau ca {@link android.preference.PreferenceScreen}.</p> 191 192 <p class="note"><strong>Lu :</strong> Nu bn mun to mt b tr a bng cho thit t 193 ca mnh, vy bn nn tch ring cc tp XML cho tng phn on.</p> 194 195 <p>Node gc cho tp XML phi l mt phn t {@link android.preference.PreferenceScreen 196 <PreferenceScreen>}. Trong phn t ny l ni bn thm tng {@link 197 android.preference.Preference}. Tng phn t con m bn thm vo trong phn t 198 {@link android.preference.PreferenceScreen <PreferenceScreen>} s xut hin nh mt mc 199 n l trong danh sch thit t.</p> 200 201 <p>V d:</p> 202 203 <pre> 204 <?xml version="1.0" encoding="utf-8"?> 205 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 206 <CheckBoxPreference 207 android:key="pref_sync" 208 android:title="@string/pref_sync" 209 android:summary="@string/pref_sync_summ" 210 android:defaultValue="true" /> 211 <ListPreference 212 android:dependency="pref_sync" 213 android:key="pref_syncConnectionType" 214 android:title="@string/pref_syncConnectionType" 215 android:dialogTitle="@string/pref_syncConnectionType" 216 android:entries="@array/pref_syncConnectionTypes_entries" 217 android:entryValues="@array/pref_syncConnectionTypes_values" 218 android:defaultValue="@string/pref_syncConnectionTypes_default" /> 219 </PreferenceScreen> 220 </pre> 221 222 <p>Trong v d ny, c mt {@link android.preference.CheckBoxPreference} v mt {@link 223 android.preference.ListPreference}. C hai mc u bao gm ba thuc tnh sau:</p> 224 225 <dl> 226 <dt>{@code android:key}</dt> 227 <dd>Thuc tnh ny c yu cu cho cc ty chn duy tr mt gi tr d liu. N quy nh kha 228 (xu) duy nht m h thng s dng khi lu gi tr ca thit t ny trong {@link 229 android.content.SharedPreferences}. 230 <p>Cc thc th duy nht m thuc tnh ny khng <em>c yu cu</em> l khi ty chn l mt 231 {@link android.preference.PreferenceCategory} hoc {@link android.preference.PreferenceScreen}, hoc 232 ty chn quy nh mt {@link android.content.Intent} gi ra (bng phn t <a href="#Intents">{@code <intent>}</a>) hoc {@link android.app.Fragment} hin th (bng thuc tnh <a href="{@docRoot}reference/android/preference/Preference.html#attr_android:fragment">{@code 233 android:fragment}</a>).</p> 234 </dd> 235 <dt>{@code android:title}</dt> 236 <dd>Thuc tnh ny cung cp mt tn hin th vi ngi dng cho thit t.</dd> 237 <dt>{@code android:defaultValue}</dt> 238 <dd>N quy nh gi tr ban u m h thng nn t trong tp {@link 239 android.content.SharedPreferences}. Bn nn cung cp mt gi tr mc nh cho tt c 240 thit t.</dd> 241 </dl> 242 243 <p> bit thng tin v tt c thuc tnh c h tr khc, hy xem ti liu {@link 244 android.preference.Preference} (v lp con tng ng).</p> 245 246 247 <div class="figure" style="width:300px"> 248 <img src="{@docRoot}images/ui/settings/settings-titles.png" alt="" /> 249 <p class="img-caption"><strong>Hnh 2.</strong> Thit t th loi 250 c tiu . <br/><b>1.</b> Th loi c quy nh bi phn t {@link 251 android.preference.PreferenceCategory <PreferenceCategory>}. <br/><b>2.</b> Tiu 252 c quy nh bng thuc tnh {@code android:title}.</p> 253 </div> 254 255 256 <p>Khi danh sch thit t ca bn vt qu khong 10 mc, bn c th mun thm tiu 257 nh ngha cc nhm thit t hoc hin th cc nhm trong mt 258 mn hnh ring. Nhng ty chn ny c m t trong cc phn sau.</p> 259 260 261 <h3 id="Groups">To nhm thit t</h3> 262 263 <p>Nu bn trnh by mt danh sch t 10 thit t tr ln, ngi dng 264 c th gp kh khn trong vic d tm, hiu v x l chng. Bn c th khc phc iu ny bng cch 265 chia mt s hoc tt c thit t thnh cc nhm, qua bin mt danh sch di thnh nhiu 266 danh sch ngn hn. Mt nhm cc thit t c lin quan c th c trnh by bng mt trong hai cch:</p> 267 268 <ul> 269 <li><a href="#Titles">S dng tiu </a></li> 270 <li><a href="#Subscreens">S dng mn hnh con</a></li> 271 </ul> 272 273 <p>Bn c th s dng mt hoc c hai k thut to nhm ny sp xp cc thit t cho ng dng ca mnh. Khi 274 quyt nh s dng ci no v lm th no chia cc thit t ca mnh, bn nn tun theo cc hng dn trong ti liu hng dn 275 <a href="{@docRoot}design/patterns/settings.html">Thit t</a> ca Thit k Android.</p> 276 277 278 <h4 id="Titles">S dng tiu </h4> 279 280 <p>Nu bn mun cung cp cc thanh chia c tiu gia cc nhm thit t (nh minh ha trong hnh 2), 281 hy t tng nhm i tng {@link android.preference.Preference} vo bn trong mt {@link 282 android.preference.PreferenceCategory}.</p> 283 284 <p>V d:</p> 285 286 <pre> 287 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 288 <PreferenceCategory 289 android:title="@string/pref_sms_storage_title" 290 android:key="pref_key_storage_settings"> 291 <CheckBoxPreference 292 android:key="pref_key_auto_delete" 293 android:summary="@string/pref_summary_auto_delete" 294 android:title="@string/pref_title_auto_delete" 295 android:defaultValue="false"... /> 296 <Preference 297 android:key="pref_key_sms_delete_limit" 298 android:dependency="pref_key_auto_delete" 299 android:summary="@string/pref_summary_delete_limit" 300 android:title="@string/pref_title_sms_delete"... /> 301 <Preference 302 android:key="pref_key_mms_delete_limit" 303 android:dependency="pref_key_auto_delete" 304 android:summary="@string/pref_summary_delete_limit" 305 android:title="@string/pref_title_mms_delete" ... /> 306 </PreferenceCategory> 307 ... 308 </PreferenceScreen> 309 </pre> 310 311 312 <h4 id="Subscreens">S dng mn hnh con</h4> 313 314 <p>Nu bn mun t cc nhm thit t vo mt mn hnh con (nh minh ha trong hnh 3), hy t nhm 315 cc i tng {@link android.preference.Preference} vo bn trong mt {@link 316 android.preference.PreferenceScreen}.</p> 317 318 <img src="{@docRoot}images/ui/settings/settings-subscreen.png" alt="" /> 319 <p class="img-caption"><strong>Hnh 3.</strong> Mn hnh con thit t. Phn t {@code 320 <PreferenceScreen>} s to 321 mt mc m, khi c chn, n s m ra mt danh sch ring hin th cc thit t lng nhau.</p> 322 323 <p>V d:</p> 324 325 <pre> 326 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 327 <!-- opens a subscreen of settings --> 328 <PreferenceScreen 329 android:key="button_voicemail_category_key" 330 android:title="@string/voicemail" 331 android:persistent="false"> 332 <ListPreference 333 android:key="button_voicemail_provider_key" 334 android:title="@string/voicemail_provider" ... /> 335 <!-- opens another nested subscreen --> 336 <PreferenceScreen 337 android:key="button_voicemail_setting_key" 338 android:title="@string/voicemail_settings" 339 android:persistent="false"> 340 ... 341 </PreferenceScreen> 342 <RingtonePreference 343 android:key="button_voicemail_ringtone_key" 344 android:title="@string/voicemail_ringtone_title" 345 android:ringtoneType="notification" ... /> 346 ... 347 </PreferenceScreen> 348 ... 349 </PreferenceScreen> 350 </pre> 351 352 353 <h3 id="Intents">S dng nh</h3> 354 355 <p>Trong mt s trng hp, bn c th mun mt mc ty chn m mt hot ng khc thay v mt 356 mn hnh thit t, chng hn nh mt trnh duyt web xem mt trang web. gi ra mt {@link 357 android.content.Intent} khi ngi dng chn mt mc ty chn, hy thm mt phn t {@code <intent>} 358 lm con ca phn t {@code <Preference>} tng ng.</p> 359 360 <p>V d, sau y l cch bn c th s dng mt mc ty chn m mt trang web:</p> 361 362 <pre> 363 <Preference android:title="@string/prefs_web_page" > 364 <intent android:action="android.intent.action.VIEW" 365 android:data="http://www.example.com" /> 366 </Preference> 367 </pre> 368 369 <p>Bn c th to c nh biu th v khng biu th bng cch s dng cc thuc tnh sau:</p> 370 371 <dl> 372 <dt>{@code android:action}</dt> 373 <dd>Hnh ng cn gn, theo mi phng php {@link android.content.Intent#setAction setAction()} 374 .</dd> 375 <dt>{@code android:data}</dt> 376 <dd>D liu cn gn, theo mi phng php {@link android.content.Intent#setData setData()}.</dd> 377 <dt>{@code android:mimeType}</dt> 378 <dd>Kiu MIME cn gn, theo mi phng php {@link android.content.Intent#setType setType()} 379 .</dd> 380 <dt>{@code android:targetClass}</dt> 381 <dd>Phn lp ca tn thnh phn, theo mi phng php {@link android.content.Intent#setComponent 382 setComponent()}.</dd> 383 <dt>{@code android:targetPackage}</dt> 384 <dd>Phn gi ca tn thnh phn, theo mi phng php {@link 385 android.content.Intent#setComponent setComponent()}.</dd> 386 </dl> 387 388 389 390 <h2 id="Activity">To mt Hot ng Ty chn</h2> 391 392 <p> hin th thit t ca bn trong mt hot ng, hy m rng lp {@link 393 android.preference.PreferenceActivity}. y l phn m rng ca lp {@link 394 android.app.Activity} truyn thng m hin th mt danh sch cc thit t da trn mt phn cp ca cc i tng {@link 395 android.preference.Preference}. {@link android.preference.PreferenceActivity} 396 s t ng duy tr cc thit t lin kt vi tng {@link 397 android.preference.Preference} khi ngi dng thc hin mt thay i.</p> 398 399 <p class="note"><strong>Lu :</strong> Nu bn ang pht trin ng dng ca mnh cho phin bn Android 3.0 v 400 cao hn, thay vo bn nn s dng {@link android.preference.PreferenceFragment}. i n phn 401 tip theo v <a href="#Fragment">S dng Phn on Ty chn</a>.</p> 402 403 <p>iu quan trng nht cn nh l bn khng c ti mt b tr dng xem trong khi gi li {@link 404 android.preference.PreferenceActivity#onCreate onCreate()}. Thay vo , bn hy gi {@link 405 android.preference.PreferenceActivity#addPreferencesFromResource addPreferencesFromResource()} 406 thm ty chn m bn khai bo trong mt tp XML vo hot ng. V d, sau y l on m ti thiu 407 cn thit cho mt {@link android.preference.PreferenceActivity} chc nng:</p> 408 409 <pre> 410 public class SettingsActivity extends PreferenceActivity { 411 @Override 412 public void onCreate(Bundle savedInstanceState) { 413 super.onCreate(savedInstanceState); 414 addPreferencesFromResource(R.xml.preferences); 415 } 416 } 417 </pre> 418 419 <p>y l on m va cho mt s ng dng bi ngay khi ngi dng sa i mt ty chn, 420 h thng s lu thay i i vi tp {@link android.content.SharedPreferences} mc nh m cc 421 thnh phn ng dng khc ca bn c th c khi bn cn kim tra thit t ca ngi dng. Tuy nhin, 422 nhiu ng dng li yu cu thm m theo di nhng thay i xy ra vi cc ty chn . 423 bit thng tin v vic theo di thay i trong tp {@link android.content.SharedPreferences}, 424 hy xem phn v <a href="#ReadingPrefs">c Ty chn</a>.</p> 425 426 427 428 429 <h2 id="Fragment">S dng Phn on Ty chn</h2> 430 431 <p>Nu bn ang pht trin cho phin bn Android 3.0 (API mc 11) tr ln, bn nn s dng mt {@link 432 android.preference.PreferenceFragment} hin th danh sch cc i tng {@link android.preference.Preference} 433 ca bn. Bn c th thm mt {@link android.preference.PreferenceFragment} vo bt k hot ng no—bn khng cn 434 s dng {@link android.preference.PreferenceActivity}.</p> 435 436 <p><a href="{@docRoot}guide/components/fragments.html">Phn on</a> cung cp mt kin trc 437 linh hot hn cho ng dng ca bn, so vi vic s dng ch cc hot ng, d loi hot ng 438 m bn ang xy dng l g. Nh vy, chng ti gi bn s dng {@link 439 android.preference.PreferenceFragment} kim sot hin th cc thit t ca mnh thay cho {@link 440 android.preference.PreferenceActivity} khi c th.</p> 441 442 <p>Vic trin khai {@link android.preference.PreferenceFragment} c th ch n gin nh 443 nh ngha phng php {@link android.preference.PreferenceFragment#onCreate onCreate()} ti mt 444 tp ty chn bng {@link android.preference.PreferenceFragment#addPreferencesFromResource 445 addPreferencesFromResource()}. V d:</p> 446 447 <pre> 448 public static class SettingsFragment extends PreferenceFragment { 449 @Override 450 public void onCreate(Bundle savedInstanceState) { 451 super.onCreate(savedInstanceState); 452 453 // Load the preferences from an XML resource 454 addPreferencesFromResource(R.xml.preferences); 455 } 456 ... 457 } 458 </pre> 459 460 <p>Khi , bn c th thm phn on ny vo mt {@link android.app.Activity} ging nh cch m bn s lm vi bt k 461 {@link android.app.Fragment} no khc. V d:</p> 462 463 <pre> 464 public class SettingsActivity extends Activity { 465 @Override 466 protected void onCreate(Bundle savedInstanceState) { 467 super.onCreate(savedInstanceState); 468 469 // Display the fragment as the main content. 470 getFragmentManager().beginTransaction() 471 .replace(android.R.id.content, new SettingsFragment()) 472 .commit(); 473 } 474 } 475 </pre> 476 477 <p class="note"><strong>Lu :</strong> {@link android.preference.PreferenceFragment} khng c mt 478 i tng {@link android.content.Context} ca chnh n. Nu bn cn mt i tng {@link android.content.Context} 479 , bn c th gi {@link android.app.Fragment#getActivity()}. Tuy nhin, hy chc chn l ch gi 480 {@link android.app.Fragment#getActivity()} khi phn on c gn km vi mt hot ng. Khi 481 phn on cha c gn km, hoc b b gn km trong khi kt thc vng i ca n, {@link 482 android.app.Fragment#getActivity()} s tr v rng.</p> 483 484 485 <h2 id="Defaults">Thit t Gi tr Mc nh</h2> 486 487 <p>Ty chn m bn to c th nh ngha mt s hnh vi quan trng cho ng dng ca bn, v th 488 bn cn phi khi to tp {@link android.content.SharedPreferences} km theo vi cc 489 gi tr mc nh cho tng {@link android.preference.Preference} khi ngi dng ln u m 490 ng dng ca bn.</p> 491 492 <p>iu u tin bn phi lm l quy nh mt gi tr mc nh cho tng i tng {@link 493 android.preference.Preference} 494 trong tp XML ca bn bng cch s dng thuc tnh {@code android:defaultValue}. Gi tr c th l bt k kiu 495 d liu no m ph hp vi i tng {@link android.preference.Preference} tng ng. V 496 d:</p> 497 498 <pre> 499 <!-- default value is a boolean --> 500 <CheckBoxPreference 501 android:defaultValue="true" 502 ... /> 503 504 <!-- default value is a string --> 505 <ListPreference 506 android:defaultValue="@string/pref_syncConnectionTypes_default" 507 ... /> 508 </pre> 509 510 <p>Khi , t phng php {@link android.app.Activity#onCreate onCreate()} trong hot ng chnh 511 —ca ng dng ca bn v trong bt k hot ng no khc m thng qua ngi dng c th vo ng dng ca bn ln 512 u tin—hy gi {@link android.preference.PreferenceManager#setDefaultValues 513 setDefaultValues()}:</p> 514 515 <pre> 516 PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false); 517 </pre> 518 519 <p>Vic gi ny trong khi {@link android.app.Activity#onCreate onCreate()} s m bo rng 520 ng dng ca bn c khi to ph hp vi cc thit t mc nh m ng dng ca bn c th cn 521 c xc nh mt s hnh vi (chng hn nh c ti xung d liu trong khi ang trn 522 mng di ng hay khng).</p> 523 524 <p>Phng php ny dng ba tham i:</p> 525 <ul> 526 <li>{@link android.content.Context} ng dng ca bn.</li> 527 <li>ID ti nguyn cho tp XML ty chn m bn mun t cc gi tr mc nh cho.</li> 528 <li>Mt boolean cho bit cc gi tr mc nh c nn c t nhiu hn mt ln hay khng. 529 <p>Khi tham i ny l <code>false</code>, h thng s t cc gi tr mc nh ch khi phng php ny cha tng c 530 gi trc y (hoc {@link android.preference.PreferenceManager#KEY_HAS_SET_DEFAULT_VALUES} 531 trong tp ty chn c chia s gi tr mc nh l sai).</p></li> 532 </ul> 533 534 <p>Min l bn t tham i th ba ny thnh <code>false</code>, bn c th gi phng php ny mt cch an ton 535 mi khi hot ng ca bn bt u m khng khng ch cc ty chn lu ca ngi dng bng cch t li chng thnh 536 mc nh. Tuy nhin, nu bn t n thnh <code>true</code>, bn s khng ch mi gi tr 537 trc bng cc gi tr mc nh.</p> 538 539 540 541 <h2 id="PreferenceHeaders">S dng Tiu Ty chn</h2> 542 543 <p>Trong vi trng hp him gp, bn c th mun thit k cc thit t ca mnh sao cho mn hnh th nht 544 ch hin th mt danh sch <a href="#Subscreens">cc mn hnh con</a> (chng hn nh trong ng dng Thit t ca h thng, 545 nh minh ha trong cc hnh 4 v 5). Khi pht trin thit k nh vy cho phin bn Android 3.0 tr ln, bn 546 nn s dng tnh nng "tiu " mi trong Android 3.0, thay v xy dng mn hnh con vi cc phn t 547 {@link android.preference.PreferenceScreen} lng nhau.</p> 548 549 <p> xy dng thit t c tiu ca mnh, bn cn:</p> 550 <ol> 551 <li>Tch ring tng nhm thit t thnh cc thc th ring ca {@link 552 android.preference.PreferenceFragment}. C th, mi nhm thit t cn mt tp XML 553 ring.</li> 554 <li>To mt tp tiu XML lit k tng nhm thit t v khai bo phn on no 555 cha danh sch thit t tng ng.</li> 556 <li>M rng lp {@link android.preference.PreferenceActivity} lu tr cc thit t ca bn.</li> 557 <li>Trin khai lnh gi li {@link 558 android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} quy nh 559 tp tiu .</li> 560 </ol> 561 562 <p>Mt li ch tuyt vi i vi vic s dng thit k ny l {@link android.preference.PreferenceActivity} 563 t ng trnh by b tr hai bng nh minh ha trong hnh 4 khi chy trn mn hnh ln.</p> 564 565 <p>Ngay c khi ng dng ca bn h tr cc phin bn Android c hn 3.0, bn c th xy dng ng dng 566 ca mnh s dng {@link android.preference.PreferenceFragment} cho mt trnh chiu hai bng trn 567 cc thit b mi hn, trong khi vn h tr phn cp a mn hnh truyn thng trn cc thit b 568 c hn (xem phn ni v <a href="#BackCompatHeaders">H tr cc phin bn c hn 569 vi tiu ty chn</a>).</p> 570 571 <img src="{@docRoot}images/ui/settings/settings-headers-tablet.png" alt="" /> 572 <p class="img-caption"><strong>Hnh 4.</strong> B tr c hai bng vi tiu . <br/><b>1.</b> 573 Tiu c nh ngha trong mt tp tiu XML. <br/><b>2.</b> Mi nhm thit t c nh ngha bi mt 574 {@link android.preference.PreferenceFragment}, c quy nh bi mt phn t {@code <header>} trong tp tiu 575 .</p> 576 577 <img src="{@docRoot}images/ui/settings/settings-headers-handset.png" alt="" /> 578 <p class="img-caption"><strong>Hnh 5.</strong> Thit b cm tay vi cc tiu thit t. Khi mt 579 mc c chn, {@link android.preference.PreferenceFragment} c lin kt s thay th 580 tiu .</p> 581 582 583 <h3 id="CreateHeaders" style="clear:left">To tp tiu </h3> 584 585 <p>Mi nhm thit t trong danh sch tiu ca bn c quy nh bi mt phn t {@code <header>} 586 n l bn trong mt phn t {@code <preference-headers>} gc. V d:</p> 587 588 <pre> 589 <?xml version="1.0" encoding="utf-8"?> 590 <preference-headers xmlns:android="http://schemas.android.com/apk/res/android"> 591 <header 592 android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentOne" 593 android:title="@string/prefs_category_one" 594 android:summary="@string/prefs_summ_category_one" /> 595 <header 596 android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentTwo" 597 android:title="@string/prefs_category_two" 598 android:summary="@string/prefs_summ_category_two" > 599 <!-- key/value pairs can be included as arguments for the fragment. --> 600 <extra android:name="someKey" android:value="someHeaderValue" /> 601 </header> 602 </preference-headers> 603 </pre> 604 605 <p>Vi thuc tnh {@code android:fragment}, mi tiu s khai bo mt thc th ca {@link 606 android.preference.PreferenceFragment} m s m khi ngi dng chn tiu .</p> 607 608 <p>Phn t {@code <extras>} cho php bn chuyn cc cp kha-gi tr sang phn on trong mt {@link 609 android.os.Bundle}. Phn on c th truy xut cc tham i bng cch gi {@link 610 android.app.Fragment#getArguments()}. Bn c th chuyn cc tham i ti phn on v nhiu 611 l do khc nhau, nhng mt l do chnh ng l s dng li cng lp con ca {@link 612 android.preference.PreferenceFragment} cho mi nhm v s dng tham i quy nh 613 tp XML ty chn no m phn on cn ti.</p> 614 615 <p>V d, sau y l mt phn on m c th c ti s dng cho nhiu nhm thit t, khi tng 616 tiu nh ngha mt tham i {@code <extra>} vi kha {@code "settings"}:</p> 617 618 <pre> 619 public static class SettingsFragment extends PreferenceFragment { 620 @Override 621 public void onCreate(Bundle savedInstanceState) { 622 super.onCreate(savedInstanceState); 623 624 String settings = getArguments().getString("settings"); 625 if ("notifications".equals(settings)) { 626 addPreferencesFromResource(R.xml.settings_wifi); 627 } else if ("sync".equals(settings)) { 628 addPreferencesFromResource(R.xml.settings_sync); 629 } 630 } 631 } 632 </pre> 633 634 635 636 <h3 id="DisplayHeaders">Hin th tiu </h3> 637 638 <p> hin th tiu ty chn, bn phi trin khai phng php gi li {@link 639 android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} v gi 640 {@link android.preference.PreferenceActivity#loadHeadersFromResource 641 loadHeadersFromResource()}. V d:</p> 642 643 <pre> 644 public class SettingsActivity extends PreferenceActivity { 645 @Override 646 public void onBuildHeaders(List<Header> target) { 647 loadHeadersFromResource(R.xml.preference_headers, target); 648 } 649 } 650 </pre> 651 652 <p>Khi ngi dng chn mt mc t danh sch tiu , h thng s m {@link 653 android.preference.PreferenceFragment} km theo.</p> 654 655 <p class="note"><strong>Lu :</strong> Khi s dng tiu ty chn, lp con {@link 656 android.preference.PreferenceActivity} ca bn khng cn trin khai phng php {@link 657 android.preference.PreferenceActivity#onCreate onCreate()}, v tc v cn thit duy nht 658 cho hot ng l ti tiu .</p> 659 660 661 <h3 id="BackCompatHeaders">H tr cc phin bn c hn vi tiu ty chn</h3> 662 663 <p>Nu ng dng ca bn h tr cc phin bn Android c hn 3.0, bn vn c th s dng tiu 664 cung cp mt b tr hai bng khi chy trn Android 3.0 tr ln. Tt c nhng vic bn cn lm l to mt 665 tp XML ty chn b sung c s dng phn t c bn {@link android.preference.Preference 666 <Preference>} ng vai tr nh mc tiu ( dng cho cc phin bn Android 667 c hn).</p> 668 669 <p>Tuy nhin, thay v m mt {@link android.preference.PreferenceScreen} mi, tng phn t {@link 670 android.preference.Preference <Preference>} s gi mt {@link android.content.Intent} ti 671 {@link android.preference.PreferenceActivity} m quy nh tp XML ty chn cn 672 ti.</p> 673 674 <p>V d, sau y l mt tp XML cho cc tiu ty chn c s dng trn Android 3.0 675 tr ln ({@code res/xml/preference_headers.xml}):</p> 676 677 <pre> 678 <preference-headers xmlns:android="http://schemas.android.com/apk/res/android"> 679 <header 680 android:fragment="com.example.prefs.SettingsFragmentOne" 681 android:title="@string/prefs_category_one" 682 android:summary="@string/prefs_summ_category_one" /> 683 <header 684 android:fragment="com.example.prefs.SettingsFragmentTwo" 685 android:title="@string/prefs_category_two" 686 android:summary="@string/prefs_summ_category_two" /> 687 </preference-headers> 688 </pre> 689 690 <p>V sau y l mt tp ty chn cung cp cng cc tiu cho cc phin bn c hn 691 Android 3.0 ({@code res/xml/preference_headers_legacy.xml}):</p> 692 693 <pre> 694 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> 695 <Preference 696 android:title="@string/prefs_category_one" 697 android:summary="@string/prefs_summ_category_one" > 698 <intent 699 android:targetPackage="com.example.prefs" 700 android:targetClass="com.example.prefs.SettingsActivity" 701 android:action="com.example.prefs.PREFS_ONE" /> 702 </Preference> 703 <Preference 704 android:title="@string/prefs_category_two" 705 android:summary="@string/prefs_summ_category_two" > 706 <intent 707 android:targetPackage="com.example.prefs" 708 android:targetClass="com.example.prefs.SettingsActivity" 709 android:action="com.example.prefs.PREFS_TWO" /> 710 </Preference> 711 </PreferenceScreen> 712 </pre> 713 714 <p>V h tr dnh cho {@code <preference-headers>} c thm trong Android 3.0, h thng s gi 715 {@link android.preference.PreferenceActivity#onBuildHeaders onBuildHeaders()} trong {@link 716 android.preference.PreferenceActivity} ca bn ch khi ang chy trn phin bn Androd 3.0 hoc cao hn. ti 717 tp tiu "k tha" ({@code preference_headers_legacy.xml}), bn phi kim tra phin bn Android 718 v, nu phin bn c hn Android 3.0 ({@link 719 android.os.Build.VERSION_CODES#HONEYCOMB}), hy gi {@link 720 android.preference.PreferenceActivity#addPreferencesFromResource addPreferencesFromResource()} 721 ti tp tiu k tha. V d:</p> 722 723 <pre> 724 @Override 725 public void onCreate(Bundle savedInstanceState) { 726 super.onCreate(savedInstanceState); 727 ... 728 729 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { 730 // Load the legacy preferences headers 731 addPreferencesFromResource(R.xml.preference_headers_legacy); 732 } 733 } 734 735 // Called only on Honeycomb and later 736 @Override 737 public void onBuildHeaders(List<Header> target) { 738 loadHeadersFromResource(R.xml.preference_headers, target); 739 } 740 </pre> 741 742 <p>Vic duy nht cn li cn lm l x l {@link android.content.Intent} m c chuyn vo 743 hot ng nhn bit tp ty chn no cn ti. V vy, hy truy xut hnh ng ca nh v so snh n vi 744 cc xu hnh ng bit m bn s dng trong tag {@code <intent>} ca XML ty chn:</p> 745 746 <pre> 747 final static String ACTION_PREFS_ONE = "com.example.prefs.PREFS_ONE"; 748 ... 749 750 @Override 751 public void onCreate(Bundle savedInstanceState) { 752 super.onCreate(savedInstanceState); 753 754 String action = getIntent().getAction(); 755 if (action != null && action.equals(ACTION_PREFS_ONE)) { 756 addPreferencesFromResource(R.xml.preferences); 757 } 758 ... 759 760 else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { 761 // Load the legacy preferences headers 762 addPreferencesFromResource(R.xml.preference_headers_legacy); 763 } 764 } 765 </pre> 766 767 <p>Lu rng cc lnh gi lin tip n {@link 768 android.preference.PreferenceActivity#addPreferencesFromResource addPreferencesFromResource()} s 769 xp chng tt c ty chn trong mt danh sch duy nht, v th hy chc chn rng n ch c gi mt ln bng cch lin kt cc 770 iu kin vi mnh else-if.</p> 771 772 773 774 775 776 <h2 id="ReadingPrefs">c Ty chn</h2> 777 778 <p>Theo mc nh, tt c ty chn ca ng dng ca bn u c lu vo mt tp c th truy cp t bt k ni no 779 trong ng dng ca bn bng cch gi phng php tnh {@link 780 android.preference.PreferenceManager#getDefaultSharedPreferences 781 PreferenceManager.getDefaultSharedPreferences()}. iu ny s tr v i tng {@link 782 android.content.SharedPreferences} cha tt c cp kha-gi tr lin kt 783 vi cc i tng {@link android.preference.Preference} c s dng trong {@link 784 android.preference.PreferenceActivity}.</p> 785 786 <p>V d, sau y l cch bn c th c mt trong cc gi tr ty chn t bt k hot ng no khc trong ng dng 787 ca mnh:</p> 788 789 <pre> 790 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); 791 String syncConnPref = sharedPref.getString(SettingsActivity.KEY_PREF_SYNC_CONN, ""); 792 </pre> 793 794 795 796 <h3 id="Listening">Theo di thay i ty chn</h3> 797 798 <p>C mt vi l do khin bn c th mun c thng bo cng sm cng tt nu ngi dng thay i mt trong cc 799 ty chn. nhn mt phng php gi li khi thay i xy ra vi bt k ty chn no, 800 hy trin khai giao din {@link android.content.SharedPreferences.OnSharedPreferenceChangeListener 801 SharedPreference.OnSharedPreferenceChangeListener} v ng k i tng theo di cho i tng 802 {@link android.content.SharedPreferences} bng cch gi {@link 803 android.content.SharedPreferences#registerOnSharedPreferenceChangeListener 804 registerOnSharedPreferenceChangeListener()}.</p> 805 806 <p>Giao din ny ch c mt phng php gi li, {@link 807 android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged 808 onSharedPreferenceChanged()}, v bn c th thy y l cch d nht trin khai giao din nh mt phn 809 hot ng ca mnh. V d:</p> 810 811 <pre> 812 public class SettingsActivity extends PreferenceActivity 813 implements OnSharedPreferenceChangeListener { 814 public static final String KEY_PREF_SYNC_CONN = "pref_syncConnectionType"; 815 ... 816 817 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, 818 String key) { 819 if (key.equals(KEY_PREF_SYNC_CONN)) { 820 Preference connectionPref = findPreference(key); 821 // Set summary to be the user-description for the selected value 822 connectionPref.setSummary(sharedPreferences.getString(key, "")); 823 } 824 } 825 } 826 </pre> 827 828 <p>Trong v d ny, phng php s kim tra xem thit t b thay i c p dng cho mt kha ty chn bit khng. N 829 s gi {@link android.preference.PreferenceActivity#findPreference findPreference()} nhn i tng 830 {@link android.preference.Preference} b thay i n c th sa i tm tt 831 ca mc thnh m t la chn ca ngi dng. C th, khi thit t l mt {@link 832 android.preference.ListPreference} hoc thit t nhiu la chn khc, bn nn gi {@link 833 android.preference.Preference#setSummary setSummary()} khi thit t thay i hin th 834 trng thi hin ti (chng hn nh thit t Ng nh minh ha trong hnh 5).</p> 835 836 <p class="note"><strong>Lu :</strong> Nh m t trong ti liu Thit k Android v <a href="{@docRoot}design/patterns/settings.html">Thit t</a>, chng ti khuyn bn nn cp nht 837 tm tt cho {@link android.preference.ListPreference} mi khi ngi dng thay i ty chn 838 m t thit t hin ti.</p> 839 840 <p> qun l vng i trong hot ng cho ph hp, chng ti khuyn rng bn nn ng k v b ng k 841 {@link android.content.SharedPreferences.OnSharedPreferenceChangeListener} ca mnh tng ng trong {@link 842 android.app.Activity#onResume} v cc lnh gi li {@link android.app.Activity#onPause}:</p> 843 844 <pre> 845 @Override 846 protected void onResume() { 847 super.onResume(); 848 getPreferenceScreen().getSharedPreferences() 849 .registerOnSharedPreferenceChangeListener(this); 850 } 851 852 @Override 853 protected void onPause() { 854 super.onPause(); 855 getPreferenceScreen().getSharedPreferences() 856 .unregisterOnSharedPreferenceChangeListener(this); 857 } 858 </pre> 859 860 <p class="caution"><strong>Ch :</strong> Khi bn gi {@link 861 android.content.SharedPreferences#registerOnSharedPreferenceChangeListener 862 registerOnSharedPreferenceChangeListener()}, trnh qun l ty chn hin 863 khng lu tr mt tham chiu mnh ti i tng theo di. Bn phi lu tr mt tham chiu 864 mnh ti i tng theo di, nu khng n s d b thu thp thng tin rc. Chng ti 865 khuyn bn nn gi mt tham chiu ti i tng theo di trong d liu thc th ca mt i tng 866 m s tn ti min l bn cn cn i tng theo di .</p> 867 868 <p>V d, trong on m sau, hm gi khng gi tham chiu ti 869 i tng theo di. Kt qu l i tng theo di s b thu thp thng tin rc, 870 v n s b li ti mt thi im khng xc nh trong tng lai:</p> 871 872 <pre> 873 prefs.registerOnSharedPreferenceChangeListener( 874 // Bad! The listener is subject to garbage collection! 875 new SharedPreferences.OnSharedPreferenceChangeListener() { 876 public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { 877 // listener implementation 878 } 879 }); 880 </pre> 881 882 <p>Thay vo , hy lu mt tham chiu ti i tng theo di trong mt trng d liu thc th ca mt 883 i tng m s tn ti min l cn cn i tng theo di :</p> 884 885 <pre> 886 SharedPreferences.OnSharedPreferenceChangeListener listener = 887 new SharedPreferences.OnSharedPreferenceChangeListener() { 888 public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { 889 // listener implementation 890 } 891 }; 892 prefs.registerOnSharedPreferenceChangeListener(listener); 893 </pre> 894 895 <h2 id="NetworkUsage">Qun l S dng Mng</h2> 896 897 898 <p>Bt u vi Android 4.0, ng dng Thit t ca h thng s cho php ngi dng xem 899 ng dng ca h ang s dng bao nhiu d liu mng khi ang tin cnh v di nn. Khi , ngi dng c th 900 v hiu ha vic s dng d liu chy ngm cho tng ng dng. trnh vic ngi dng v hiu ha truy cp d liu 901 ca ng dng ca bn t di nn, bn nn s dng kt ni d liu mt cch hiu qu v cho php 902 ngi dng tinh chnh mc s dng d liu cho ng dng ca bn thng qua thit t ng dng.<p> 903 904 <p>V d, bn c th cho php ngi dng kim sot tn sut ng dng ca bn ng b d liu, ng dng ca bn 905 ch c thc hin ti ln/ti xung khi trn Wi-Fi, ng dng ca bn s dng d liu trong khi ang chuyn vng d liu, v.v... hay khng. Vi 906 nhng kim sot ny, ngi dng s t c kh nng v hiu ha truy cp d liu ca ng dng ca bn 907 hn nhiu khi h t gn mc gii hn t ra trong Thit t h thng, v thay vo , h c th kim sot chnh xc 908 lng d liu m ng dng ca bn s dng.</p> 909 910 <p>Sau khi bn thm cc ty chn cn thit trong {@link android.preference.PreferenceActivity} 911 ca mnh kim sot cc thi quen d liu ca ng dng ca bn, bn nn thm mt b lc nh cho {@link 912 android.content.Intent#ACTION_MANAGE_NETWORK_USAGE} trong tp bn k khai ca mnh. V d:</p> 913 914 <pre> 915 <activity android:name="SettingsActivity" ... > 916 <intent-filter> 917 <action android:name="android.intent.action.MANAGE_NETWORK_USAGE" /> 918 <category android:name="android.intent.category.DEFAULT" /> 919 </intent-filter> 920 </activity> 921 </pre> 922 923 <p>B lc nh ny cho h thng bit rng y l hot ng kim sot mc s dng d liu 924 ca ng dng ca bn. V th, khi ngi dng kim tra lng d liu m ng dng ca bn ang dng t ng dng 925 Thit t ca h thng, s c mt nt <em>Xem thit t ng dng</em> khi chy 926 {@link android.preference.PreferenceActivity} ca bn, v th ngi dng c th tinh chnh lng d liu m ng dng ca bn 927 dng.</p> 928 929 930 931 932 933 934 935 <h2 id="Custom">Xy dng mt Thit t Ty chnh</h2> 936 937 <p>Khun kh Android bao gm nhiu lp con {@link android.preference.Preference} m 938 cho php bn xy dng mt UI cho mt vi loi thit t khc nhau. 939 Tuy nhin, bn c th khm ph thit t mnh cn m cha c gii php tch hp sn, chng hn nh mt 940 b chn s hay b chn ngy. Trong trng hp nh vy, bn s cn to mt ty chn ty chnh bng cch m rng 941 lp {@link android.preference.Preference} hoc mt trong cc lp con khc.</p> 942 943 <p>Khi bn m rng lp {@link android.preference.Preference}, c mt vi iu quan trng 944 m bn cn lm:</p> 945 946 <ul> 947 <li>Quy nh giao din ngi dng s xut hin khi ngi dng chn thit t.</li> 948 <li>Lu gi tr ca thit t khi ph hp.</li> 949 <li>Khi to {@link android.preference.Preference} bng gi tr hin ti (hoc mc nh) 950 khi xt ti dng xem.</li> 951 <li>Cung cp gi tr mc nh khi h thng yu cu.</li> 952 <li>Nu {@link android.preference.Preference} cung cp UI ca chnh mnh (chng hn nh mt hp thoi), hy lu 953 v khi phc trng thi x l cc thay i trong vng i (chng hn nh khi ngi dng xoay mn hnh).</li> 954 </ul> 955 956 <p>Cc phn sau m t cch hon thnh tng tc v ny.</p> 957 958 959 960 <h3 id="CustomSelected">Quy nh mt giao din ngi dng</h3> 961 962 <p>Nu bn trc tip m rng lp {@link android.preference.Preference}, bn cn trin khai 963 {@link android.preference.Preference#onClick()} nh ngha hnh ng xy ra khi ngi dng 964 chn mc. Tuy nhin, hu ht cc thit t ty chnh s m rng {@link android.preference.DialogPreference} 965 hin th mt hp thoi, iu ny lm n gin ha quy trnh. Khi bn m rng {@link 966 android.preference.DialogPreference}, bn phi gi {@link 967 android.preference.DialogPreference#setDialogLayoutResource setDialogLayoutResourcs()} trong khi ang trong 968 hm dng lp quy nh b tr cho hp thoi.</p> 969 970 <p>V d, sau y l hm dng cho mt {@link 971 android.preference.DialogPreference} ty chnh m khai bo b tr v quy nh vn bn cho 972 cc nt hp thoi tch cc v tiu cc mc nh:</p> 973 974 <pre> 975 public class NumberPickerPreference extends DialogPreference { 976 public NumberPickerPreference(Context context, AttributeSet attrs) { 977 super(context, attrs); 978 979 setDialogLayoutResource(R.layout.numberpicker_dialog); 980 setPositiveButtonText(android.R.string.ok); 981 setNegativeButtonText(android.R.string.cancel); 982 983 setDialogIcon(null); 984 } 985 ... 986 } 987 </pre> 988 989 990 991 <h3 id="CustomSave">Lu gi tr ca thit t</h3> 992 993 <p>Bn c th lu mt gi tr cho thit t vo bt c lc no bng cch gi mt trong cc phng php ca lp {@link 994 android.preference.Preference}, {@code persist*()}, chng hn nh {@link 995 android.preference.Preference#persistInt persistInt()} nu gi tr ca thit t l mt s nguyn hoc 996 {@link android.preference.Preference#persistBoolean persistBoolean()} lu mt boolean.</p> 997 998 <p class="note"><strong>Lu :</strong> Mi {@link android.preference.Preference} ch c th lu mt 999 kiu d liu, v th bn phi s dng phng php {@code persist*()} ph hp cho kiu d liu c s dng bi 1000 {@link android.preference.Preference} ty chnh ca mnh.</p> 1001 1002 <p>Thi im bn chn duy tr thit t c th ph thuc vo lp {@link 1003 android.preference.Preference} no m bn m rng. Nu m rng {@link 1004 android.preference.DialogPreference}, khi bn nn duy tr gi tr ch khi hp thoi 1005 ng li do kt qu tch cc (ngi dng chn nt "OK").</p> 1006 1007 <p>Khi {@link android.preference.DialogPreference} ng li, h thng s gi phng php {@link 1008 android.preference.DialogPreference#onDialogClosed onDialogClosed()}. Phng php bao gm mt 1009 tham i boolean quy nh xem ngi dng c tr v kt qu "tch cc" hay khng—nu kt qu l 1010 <code>true</code>, khi , ngi dng chn nt tch cc v bn nn lu gi tr mi ny. V 1011 d:</p> 1012 1013 <pre> 1014 @Override 1015 protected void onDialogClosed(boolean positiveResult) { 1016 // When the user selects "OK", persist the new value 1017 if (positiveResult) { 1018 persistInt(mNewValue); 1019 } 1020 } 1021 </pre> 1022 1023 <p>Trong v d ny, <code>mNewValue</code> l mt thnh vin lp lu gi gi tr 1024 hin ti ca thit t. Vic gi {@link android.preference.Preference#persistInt persistInt()} s lu gi tr vo 1025 tp {@link android.content.SharedPreferences} (t ng s dng kha m 1026 c quy nh trong tp XML cho {@link android.preference.Preference} ny).</p> 1027 1028 1029 <h3 id="CustomInitialize">Khi to gi tr hin ti</h3> 1030 1031 <p>Khi h thng thm {@link android.preference.Preference} ca bn vo mn hnh, n 1032 gi {@link android.preference.Preference#onSetInitialValue onSetInitialValue()} thng bo 1033 vi bn xem thit t c gi tr c duy tr hay khng. Nu khng c gi tr c duy tr, lnh gi ny s cung cp 1034 cho bn gi tr mc nh.</p> 1035 1036 <p>Phng php {@link android.preference.Preference#onSetInitialValue onSetInitialValue()} chuyn mt 1037 boolean, <code>restorePersistedValue</code>, cho bit liu gi tr c duy tr 1038 cho thit t hay khng. Nu n l <code>true</code>, khi bn nn truy xut gi tr c duy tr bng cch gi 1039 mt trong cc phng php ca lp {@link 1040 android.preference.Preference}, {@code getPersisted*()}, chng hn nh {@link 1041 android.preference.Preference#getPersistedInt getPersistedInt()} i vi mt gi tr s nguyn. Bn s 1042 thng mun truy xut gi tr c duy tr sao cho bn c th cp nht UI cho ph hp phn nh 1043 gi tr lu trc .</p> 1044 1045 <p>Nu <code>restorePersistedValue</code> l <code>false</code>, vy bn 1046 nn s dng gi tr mc nh c chuyn trong tham i th hai.</p> 1047 1048 <pre> 1049 @Override 1050 protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) { 1051 if (restorePersistedValue) { 1052 // Restore existing state 1053 mCurrentValue = this.getPersistedInt(DEFAULT_VALUE); 1054 } else { 1055 // Set default state from the XML attribute 1056 mCurrentValue = (Integer) defaultValue; 1057 persistInt(mCurrentValue); 1058 } 1059 } 1060 </pre> 1061 1062 <p>Mi phng php {@code getPersisted*()} s ly mt tham i quy nh 1063 gi tr mc nh s s dng trong trng hp thc s khng c gi tr c duy tr hoc kha khng tn ti. Trong 1064 v d trn, mt hng s cc b c s dng quy nh gi tr mc nh trong trng hp {@link 1065 android.preference.Preference#getPersistedInt getPersistedInt()} khng th tr v mt gi tr c duy tr.</p> 1066 1067 <p class="caution"><strong>Ch :</strong> Bn <strong>khng th</strong> s dng 1068 <code>defaultValue</code> lm gi tr mc nh trong phng php {@code getPersisted*()}, bi 1069 gi tr ca n lun rng khi <code>restorePersistedValue</code> l <code>true</code>.</p> 1070 1071 1072 <h3 id="CustomDefault">Cung cp mt gi tr mc nh</h3> 1073 1074 <p>Nu trng hp lp {@link android.preference.Preference} ca bn quy nh mt gi tr mc nh 1075 (vi thuc tnh {@code android:defaultValue}), khi h thng 1076 s gi {@link android.preference.Preference#onGetDefaultValue 1077 onGetDefaultValue()} khi n khi to i tng truy xut gi tr. Bn phi 1078 trin khai phng php ny h thng lu gi tr mc nh trong {@link 1079 android.content.SharedPreferences}. V d:</p> 1080 1081 <pre> 1082 @Override 1083 protected Object onGetDefaultValue(TypedArray a, int index) { 1084 return a.getInteger(index, DEFAULT_VALUE); 1085 } 1086 </pre> 1087 1088 <p>Cc tham i ca phng php cung cp mi th bn cn: mng thuc tnh v v tr ch mc 1089 ca {@code android:defaultValue} m bn phi truy xut. L do bn phi trin khai 1090 phng php ny nhm trch xut gi tr mc nh t thuc tnh l bi bn phi quy nh 1091 mt gi tr mc nh cc b cho thuc tnh trong trng hp gi tr khng c nh ngha.</p> 1092 1093 1094 1095 <h3 id="CustomSaveState">Lu v khi phc trng thi ca Ty chn</h3> 1096 1097 <p>Ging nh {@link android.view.View} trong mt b tr, lp con {@link android.preference.Preference} 1098 ca bn chu trch nhim lu v khi phc trng thi ca n trong trng hp hot ng hoc phn on 1099 c khi ng li (chng hn nh khi ngi dng xoay mn hnh). lu v khi phc 1100 trng thi ca lp {@link android.preference.Preference} ca bn cho ng, bn phi trin khai cc 1101 phng php gi li vng i {@link android.preference.Preference#onSaveInstanceState 1102 onSaveInstanceState()} v {@link 1103 android.preference.Preference#onRestoreInstanceState onRestoreInstanceState()}.</p> 1104 1105 <p>Trng thi ca {@link android.preference.Preference} ca bn c nh ngha bi mt i tng m trin khai 1106 giao din {@link android.os.Parcelable}. Khun kh Android s cung cp mt i tng nh vy cho bn 1107 nh mt im bt u nh ngha i tng trng thi ca bn: lp {@link 1108 android.preference.Preference.BaseSavedState}.</p> 1109 1110 <p> nh ngha cch thc lp {@link android.preference.Preference} ca bn lu trng thi ca n 1111 hy m rng lp {@link android.preference.Preference.BaseSavedState}. Bn cn khng ch ch 1112 mt vi phng php v nh ngha i tng {@link android.preference.Preference.BaseSavedState#CREATOR} 1113 .</p> 1114 1115 <p>i vi hu ht ng dng, bn c th sao chp trin khai sau v ch cn thay i cc dng 1116 x l {@code value} nu lp con {@link android.preference.Preference} ca bn lu mt kiu 1117 d liu khc s nguyn.</p> 1118 1119 <pre> 1120 private static class SavedState extends BaseSavedState { 1121 // Member that holds the setting's value 1122 // Change this data type to match the type saved by your Preference 1123 int value; 1124 1125 public SavedState(Parcelable superState) { 1126 super(superState); 1127 } 1128 1129 public SavedState(Parcel source) { 1130 super(source); 1131 // Get the current preference's value 1132 value = source.readInt(); // Change this to read the appropriate data type 1133 } 1134 1135 @Override 1136 public void writeToParcel(Parcel dest, int flags) { 1137 super.writeToParcel(dest, flags); 1138 // Write the preference's value 1139 dest.writeInt(value); // Change this to write the appropriate data type 1140 } 1141 1142 // Standard creator object using an instance of this class 1143 public static final Parcelable.Creator<SavedState> CREATOR = 1144 new Parcelable.Creator<SavedState>() { 1145 1146 public SavedState createFromParcel(Parcel in) { 1147 return new SavedState(in); 1148 } 1149 1150 public SavedState[] newArray(int size) { 1151 return new SavedState[size]; 1152 } 1153 }; 1154 } 1155 </pre> 1156 1157 <p>Vi trin khai {@link android.preference.Preference.BaseSavedState} bn trn c thm 1158 vo ng dng ca bn (thng di dng mt lp con ca lp con {@link android.preference.Preference} ca bn), khi 1159 bn cn trin khai cc phng php {@link android.preference.Preference#onSaveInstanceState 1160 onSaveInstanceState()} v {@link 1161 android.preference.Preference#onRestoreInstanceState onRestoreInstanceState()} cho lp con 1162 {@link android.preference.Preference} ca mnh.</p> 1163 1164 <p>V d:</p> 1165 1166 <pre> 1167 @Override 1168 protected Parcelable onSaveInstanceState() { 1169 final Parcelable superState = super.onSaveInstanceState(); 1170 // Check whether this Preference is persistent (continually saved) 1171 if (isPersistent()) { 1172 // No need to save instance state since it's persistent, 1173 // use superclass state 1174 return superState; 1175 } 1176 1177 // Create instance of custom BaseSavedState 1178 final SavedState myState = new SavedState(superState); 1179 // Set the state's value with the class member that holds current 1180 // setting value 1181 myState.value = mNewValue; 1182 return myState; 1183 } 1184 1185 @Override 1186 protected void onRestoreInstanceState(Parcelable state) { 1187 // Check whether we saved the state in onSaveInstanceState 1188 if (state == null || !state.getClass().equals(SavedState.class)) { 1189 // Didn't save the state, so call superclass 1190 super.onRestoreInstanceState(state); 1191 return; 1192 } 1193 1194 // Cast state to custom BaseSavedState and pass to superclass 1195 SavedState myState = (SavedState) state; 1196 super.onRestoreInstanceState(myState.getSuperState()); 1197 1198 // Set this Preference's widget to reflect the restored state 1199 mNumberPicker.setValue(myState.value); 1200 } 1201 </pre> 1202 1203