新建MyPreferenceActivity繼承PreferenceActivity
res目錄下新建xml文件聘萨,xml目錄下新建mypre.xml
listpreference需要在values下新建mylistpreference.xml
代碼:
activity_main.xml:
Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="修改首選項"
android:id="@+id/btn"
android:layout_centerHorizontal="true"
android:layout_marginTop="165dp"/>
xml->mypre.xml:
<?xml version="1.0"encoding="utf-8"?>
<PreferenceScreenxmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="checkbox"
android:title="是否開啓"
android:summaryOn="已經(jīng)開啓"
android:summaryOff="已經(jīng)關閉"
/>
<ListPreference
android:key="list"
android:title="選擇一個選項"
android:summary="請點擊選擇"
android:entries="@array/entries"
android:entryValues="@array/values"
/>
<EditTextPreference
android:key="text"
android:dialogTitle="請輸入你的名字"
android:dialogMessage="有勞了"
android:summary="請再次輸入"
android:title="請輸入"
/>
values->mylistPreference.xml
<?xml version="1.0"encoding="utf-8"?>
<resources>
<string-array name="entries">
<item>JAVA</item>
<item>Swift</item>
<item>C#</item>
</string-array>
<string-array name="values">
<item>Eclipse</item>
<item>Xcode</item>
<item>Visual Studio</item>
</string-array>
<resources>
MyPreference.class
public classMyPreferenceActivityextendsPreferenceActivity {
//checkBoxPreference
//listPreference
//edittextPreference
PreferenceManagermanager;
CheckBoxPreferencecheckBoxPreference;
ListPreferencelistPreference;
EditTextPreferenceeditTextPreference;
@Override
protected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.myfer);
manager= getPreferenceManager();
checkBoxPreference= (CheckBoxPreference)manager.findPreference("checkbox");
Toast.makeText(getApplicationContext(),"當前的狀態(tài)為:"+checkBoxPreference.isChecked(),Toast.LENGTH_LONG).show();
listPreference= (ListPreference)manager.findPreference("list");
Toast.makeText(getApplicationContext(),listPreference.getEntry()+"的開發(fā)環(huán)境為:"+listPreference.getValue(),Toast.LENGTH_LONG).show();
editTextPreference= (EditTextPreference)manager.findPreference("text");
Toast.makeText(getApplicationContext(),"您輸入的內(nèi)容為"+editTextPreference.getText(),Toast.LENGTH_LONG).show();
}
}
MainActivity.class
findViewById(R.id.btn).setOnClickListener(newView.OnClickListener() {
@Override
public voidonClick(View view) {
startActivity(newIntent(getApplicationContext(),MyPreferenceActivity.class));
}
});
效果圖: