新建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="已經開啓"
android:summaryOff="已經關閉"
/>
<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(),"当前的状态为:"+checkBoxPreference.isChecked(),Toast.LENGTH_LONG).show();
listPreference= (ListPreference)manager.findPreference("list");
Toast.makeText(getApplicationContext(),listPreference.getEntry()+"的开发环境为:"+listPreference.getValue(),Toast.LENGTH_LONG).show();
editTextPreference= (EditTextPreference)manager.findPreference("text");
Toast.makeText(getApplicationContext(),"您输入的内容为"+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));
}
});
效果图: