Android设置Settings实现:PreferenceActivity【1】
Android的设置Settings功能比较常见,通常可以考虑使用PreferenceActivity实现。
PreferenceActivity需要从res/xml加载(addPreferencesFromResource)一个定义好的Preference的xml文件。比如preferences.xml:
android:dialogTitle="list dialog title"
android:entries="@array/citys"
android:entryValues="@array/citys"
android:key="list_key"
android:summary="list summary"
android:title="list title" />
android:defaultValue="缺省值1"
android:key="edit_text_key_1"
android:summary="edit summary"
android:title="edit text 1" />
android:defaultValue="true"
android:key="checkbox_key"
android:summary="checkbox summary"
android:title="checkbox title" />
android:summary="http://blog.csdn.net/zhangphil"
android:title="浏览网页" >
android:action="android.intent.action.VIEW"
android:data="http://blog.csdn.net/zhangphil" />
android:key="preference_screen_2_key"
android:persistent="false"
android:title="PreferenceScreen 2" >
android:defaultValue="缺省值2"
android:key="edit_text_key_2"
android:summary="edit summary"
android:title="edit text 2" />
其中需要的数组资源citys在res/values中的arrays.xml中定义好:
成都
北京
上海
上层Java代码:
package zhangphil.settings;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends PreferenceActivity {
private MyOnSharedPreferenceChangeListener mOnSharedPreferenceChangeListener = new MyOnSharedPreferenceChangeListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 通用的读取设置的某个值的方法
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String s = sharedPreferences.getString("edit_text_key_2", "暂时为空");
Log.d("edit_text_key_2", s);
// 添加设置的选项
addPreferencesFromResource(R.xml.preferences);
// 注册添加设置的项数据发生变化时候的监听
sharedPreferences.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);
}
@Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);
}
@Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(mOnSharedPreferenceChangeListener);
}
private class MyOnSharedPreferenceChangeListener implements OnSharedPreferenceChangeListener {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Toast.makeText(getApplication(), key, Toast.LENGTH_SHORT).show();
}
}
}
代码运行结果: