首页 > 代码库 > Android 代码实现preference组件
Android 代码实现preference组件
Preference主要实现一些配置数据,一些我们上次点击选择的内容,我们希望在下次应用调起的时候依然有效,无须用户再一次进行配置或选择。Android提供preference这个键值对的方式来处理这种情况,自动保存这些数据,并立时生效,同时Android提供一种类似的layout的方式来进行Preference的布局。
Preference组件有ListPreference,EditTextPreference,CheckBoxPreference和SwitchPreference,相对于View中的ListView,EditText,CheckBox,Switch和RingtonePreference .
1.介绍Preference组件的相关属性
android:key : 每个Preference控件独一无二的”ID”,唯一表示此Preference。
android:defaultValue : 默认值。 例如,CheckPreference的默认值可为”true”,默认为选中状态;
EditTextPreference的默认值可为”110”。
android:enabled : 表示该Preference是否可用状态。
android:title : 每个Preference在PreferenceScreen布局上显示的标题——大标题
android:summary : 每个Preference在PreferenceScreen布局上显示的标题——小标题(可以没有)
android:persistent: 表示Preference元素所对应的值是否写入sharedPreferen文件中,如果是true,则表示写
入;否则,则表示不写入该Preference元素的值。
android:dependency: 表示一个Preference(用A表示)的可用状态依赖另外一个Preference(用B表示)。B可用,
则A可用;B不可用,则A不可用。
android:disableDependentsState: 与android:dependency相反。B可用,则A不可用;B不可用,则A可用。
特性:ListPreference
android:dialogTitle:弹出控件对话框时显示的标题
android:entries:类型为array,控件欲显示的文本
android:entryValues:类型为array,与文本相对应的key-value键值对,value保存至sharedPreference文件
RingtonePreference
android:ringtoneType:响铃的铃声类型,主要有:ringtone(音乐)、notification(通知)、alarm(闹铃)
、all(所有可用声 音类型)。
android:showDefault :默认铃声,可以使用系统(布尔值---true,false)的或者自定义的铃声
android:showSilent :指定铃声是否为静音。指定铃声包括系统默认铃声或者自定义的铃声
2.实例实现上述所讲控件
1> 代码目录结构
2>效果图
3>xml相关文件
a.xml-> setting_preference.xml
Preference的xml文件不是放在res->layout下,而是需要新建一个xml文件夹,将setting_preference.xml放置在该xml文件夹下:
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <PreferenceCategory android:title="第一项" > <ListPreference android:defaultValue=http://www.mamicode.com/"Green">
b.layout->activity_main.xml<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" > <Button android:id="@+id/setting_btn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="设置" /> <Button android:id="@+id/show_setting_info_btn" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="显示设置信息" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="显示设置信息:" android:textColor="#FF0000" android:textSize="20sp" /> <TextView android:id="@+id/show_info_tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textSize="20sp" /> </LinearLayout>c.layout->activity_about.xml<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="fill_parent" android:text="welcome to my preference" android:textSize="20sp" android:gravity="center" ></TextView> </LinearLayout>d.value->array.xml<?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="my_color_array"> <item>Red</item> <item>Green</item> <item>Bule</item> </string-array> </resources>
4>. java代码实现a. 常量ConstantUtil.java
package com.example.settingdemo; public class ConstantUtil { public static final String LIST_KEY = "list_key"; public static final String EDIT_TEXT_KEY = "edit_text_key"; public static final String CHECK_BOX_KEY = "check_box_key"; public static final String SWITCH_KEY = "switch_key"; public static final String RING_TONE_KEY = "ring_tone_key"; public static final String PREFERENCE_KEY = "preference_key"; public static final String MY_PREFERENCE_KEY = "my_preference_key"; }
b. 主界面MainActivity.javapackage com.example.settingdemo; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener { private Button settingBtn, showSettingInfoBtn; private TextView showInfoTv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); settingBtn = (Button) this.findViewById(R.id.setting_btn); showSettingInfoBtn = (Button) this .findViewById(R.id.show_setting_info_btn); showInfoTv = (TextView) this.findViewById(R.id.show_info_tv); settingBtn.setOnClickListener(this); showSettingInfoBtn.setOnClickListener(this); } @Override public void onResume() { super.onResume(); showSettingInfo(); } /** * 显示设置信息 */ private void showSettingInfo() { SharedPreferences share = PreferenceManager .getDefaultSharedPreferences(this); StringBuffer info = new StringBuffer(); String listInfo = share.getString(ConstantUtil.LIST_KEY, "Green"); String editTextInfo = share.getString(ConstantUtil.EDIT_TEXT_KEY, "this is editTextPreference"); boolean checkBoxInfo = share.getBoolean(ConstantUtil.CHECK_BOX_KEY, true); boolean switchInfo = share.getBoolean(ConstantUtil.SWITCH_KEY, true); String ringtoneInfo = share.getString(ConstantUtil.RING_TONE_KEY, "默认铃声"); info.append("ListInfo:").append(listInfo).append("\n") .append("editTextInfo:").append(editTextInfo).append("\n") .append("checkBoxInfo:").append(checkBoxInfo).append("\n") .append("switchInfo:").append(switchInfo).append("\n") .append("ringtoneInfo:").append(ringtoneInfo).append("\n"); showInfoTv.setText(info.toString()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.setting_btn: Intent intent = new Intent(MainActivity.this, SettingActivity.class); startActivity(intent); break; case R.id.show_setting_info_btn: showSettingInfo(); break; } } }
c. 设置界面SettingActivity.javapackage com.example.settingdemo; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.RingtonePreference; import android.preference.SwitchPreference; import android.widget.Toast; public class SettingActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener,OnPreferenceClickListener{ private ListPreference mListPreference; private EditTextPreference mEditTextPreference; private CheckBoxPreference mCheckBoxPreference; private SwitchPreference mSwitchPreference; private Preference mPreference; private RingtonePreference mRingtonePreference; @SuppressWarnings("deprecation") @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); this.addPreferencesFromResource(R.xml.setting_preference); initPreference(); } @SuppressWarnings("deprecation") private void initPreference(){ mListPreference = (ListPreference) this.findPreference(ConstantUtil.LIST_KEY); mEditTextPreference = (EditTextPreference) this.findPreference(ConstantUtil.EDIT_TEXT_KEY); mCheckBoxPreference = (CheckBoxPreference) this.findPreference(ConstantUtil.CHECK_BOX_KEY); mSwitchPreference = (SwitchPreference) this.findPreference(ConstantUtil.SWITCH_KEY); mPreference = (Preference) this.findPreference(ConstantUtil.PREFERENCE_KEY); mRingtonePreference = (RingtonePreference) this.findPreference(ConstantUtil.RING_TONE_KEY); mPreference.setOnPreferenceClickListener(this); } @SuppressWarnings("deprecation") @Override public void onResume(){ super.onResume(); SharedPreferences share = this.getPreferenceScreen().getSharedPreferences(); setDefaultSummary(share); share.registerOnSharedPreferenceChangeListener(this); } @SuppressWarnings("deprecation") @Override public void onPause(){ super.onPause(); this.getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); } /** * 设置组件小标题 * @param share */ private void setDefaultSummary(SharedPreferences share){ mListPreference.setSummary(share.getString(ConstantUtil.LIST_KEY, "Green")); mEditTextPreference.setSummary(share.getString(ConstantUtil.EDIT_TEXT_KEY, "this is editTextPreference")); mRingtonePreference.setSummary(share.getString(ConstantUtil.RING_TONE_KEY, "默认铃声")); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // TODO Auto-generated method stub if(ConstantUtil.LIST_KEY.equals(key)){ mListPreference.setSummary(mListPreference.getEntry()); }else if(ConstantUtil.EDIT_TEXT_KEY.equals(key)){ mEditTextPreference.setSummary(sharedPreferences.getString(key, "this is editTextPreference")); }else if(ConstantUtil.RING_TONE_KEY.equals(key)){ mRingtonePreference.setSummary(sharedPreferences.getString(key, "默认铃声")); } } @Override public boolean onPreferenceClick(Preference preference) { // TODO Auto-generated method stub if(ConstantUtil.PREFERENCE_KEY.equals(preference.getKey())){ Intent intent = new Intent(SettingActivity.this,AboutActivity.class); startActivity(intent); }else if(ConstantUtil.MY_PREFERENCE_KEY.equals(preference.getKey())){ Toast.makeText(this, "点击MyPreference", Toast.LENGTH_SHORT).show(); } return false; } }
d.跳转界面AboutActivity.javapackage com.example.settingdemo; import android.app.Activity; import android.os.Bundle; public class AboutActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); } }
5>. 清单AndroidManifest.xml<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.settingdemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.settingdemo.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.settingdemo.SettingActivity"></activity> <activity android:name="com.example.settingdemo.AboutActivity"></activity> </application> </manifest>
至此,本文已完成,大家可以试试。
源代码下载链接:http://download.csdn.net/detail/a123demi/7564135