編輯:關於Android編程
首選項這個名詞對於熟悉Android的朋友們一定不會感到陌生,它經常用來設置軟件的運行參數。
Android提供了一種健壯並且靈活的框架來處理首選項。它提供了簡單的API來隱藏首選項的讀取和持久化,並且提供了一個優雅的首選項界面。
幾種常見的首選項:
(1)CheckBoxPreference:用來打開或關閉某個功能
(2)ListPreference:用來從多個選項中選擇一個值;
(3)EditTextPreference:用來配置一段文字信息;
(4)Preference:用來執行相關的自定義操作(上圖中的清除緩存、歷史記錄、表單、cookie都屬於此項);
(5)RingtonePreference:專門用來為用戶設置鈴聲。
當我們使用首選項框架時,用戶每更改一項的值後,系統就會立即在/data/data/[PACKAGE_NAME]/shared_prefs下生成一個[PACKAGE_NAME]_preferences.xml的文件,文件會記錄最新的配置信息。
那麼本文要講的就是其中的ListPreference,以及通過PreferenceFragment來使用自定義的ListPreference。
1. 自定義屬性
添加文件res/values/attrs.xml,內容如下:
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="IconListPreference"> <attr name="entryIcons" format="reference" /> </declare-styleable> </resources>
說明:
(01) name="IconListPreference",與自定義的ListPreference類的名稱相對應。後面會實現一個繼承於ListPreference的IconListPreference.java。
(02) name="entryIcons",這是屬性的名稱。
(03) format="reference",這描述屬性的值是引用類型。因為,後面會根據資源id設置該屬性,所以將屬性格式設為reference。如果是顏色,設為format="color";如果是布爾類型,format="boolean";如果是字符串,設為format="string"。
2. 自定義ListPreference
2.1 構造函數
public IconListPreference(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
// 獲取自定義的屬性(attrs.xml中)對應行的TypedArray
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.IconListPreference);
// 獲取entryIcons屬性對應的值
int iconResId = a.getResourceId(R.styleable.IconListPreference_entryIcons, -1);
if (iconResId != -1) {
setEntryIcons(iconResId);
}
// 獲取Preferece對應的key
mKey = getKey();
// 獲取SharedPreferences
mPref = PreferenceManager.getDefaultSharedPreferences(context);
// 獲取SharedPreferences.Editor
mEditor = mPref.edit();
// 獲取Entry
// 注意:如果配置文件中沒有android:entries屬性,則getEntries()為空;
mEntries = getEntries();
// 獲取Entry對應的值
// 注意:如果配置文件中沒有android:entryValues屬性,則getEntries()為空
mEntryValues = getEntryValues();
// 獲取該ListPreference保存的值
String value = mPref.getString(mKey, "");
mPosition = findIndexOfValue(value);
// 設置Summary
if (mPosition!=-1) {
setSummary(mEntries[mPosition]);
setIcon(mEntryIcons[mPosition]);
}
a.recycle();
}
說明:
(01) 首先,根據obtainStyledAttributes()能獲取自定義屬性對應的TypedArray對象。
(02) 在自定義屬性中,entryIcons對應的類名是IconListPreference。因為需要通過"類名"_"屬性名",即IconListPreference_entryIcons的方式來獲取資源信息。
(03) getKey()是獲取Preferece對應的Key。該Key是Preference對象的唯一標識。
(04) getEntries()是獲取Preferece的Entry數組。
(05) getEntryValues()是獲取Preferece的Entry對應的值的數組。
(06) setSummary()是設置Preferece的summary標題內容。
(07) setIcon()是設置Preferece的圖標。
2.2 自定義ListPreference中圖片相關代碼
/**
* 設置圖標:icons數組
*/
private void setEntryIcons(int[] entryIcons) {
mEntryIcons = entryIcons;
}
/**
* 設置圖標:根據icon的id數組
*/
public void setEntryIcons(int entryIconsResId) {
TypedArray icons = getContext().getResources().obtainTypedArray(entryIconsResId);
int[] ids = new int[icons.length()];
for (int i = 0; i < icons.length(); i++)
ids[i] = icons.getResourceId(i, -1);
setEntryIcons(ids);
icons.recycle();
}
說明:這兩個函數是讀取圖片信息的。
2.3 自定義ListPreference彈出的列表選項
@Override
protected void onPrepareDialogBuilder(Builder builder) {
super.onPrepareDialogBuilder(builder);
IconAdapter adapter = new IconAdapter(mContext);
builder.setAdapter(adapter, null);
}
說明:點擊ListPreference,會彈出一個列表對話框。通過重寫onPrepareDialogBuilder(),我們可以自定義彈出的列表對話框。這裡是通過IconAdapter來顯示的。
public class IconAdapter extends BaseAdapter{
private LayoutInflater mInflater;
public IconAdapter(Context context){
this.mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return mEntryIcons.length;
}
@Override
public Object getItem(int arg0) {
return null;
}
@Override
public long getItemId(int arg0) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.icon_adapter, parent, false);
holder.layout = (LinearLayout)convertView.findViewById(R.id.icon_layout);
holder.img = (ImageView)convertView.findViewById(R.id.icon_img);
holder.info = (TextView)convertView.findViewById(R.id.icon_info);
holder.check = (RadioButton)convertView.findViewById(R.id.icon_check);
convertView.setTag(holder);
}else {
holder = (ViewHolder)convertView.getTag();
}
holder.img.setBackgroundResource(mEntryIcons[position]);
holder.info.setText(mEntries[position]);
holder.check.setChecked(mPosition == position);
final ViewHolder fholder = holder;
final int fpos = position;
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.requestFocus();
// 選中效果
fholder.layout.setBackgroundColor(Color.CYAN);
// 更新mPosition
mPosition = fpos;
// 更新Summary
IconListPreference.this.setSummary(mEntries[fpos]);
IconListPreference.this.setIcon(mEntryIcons[fpos]);
// 更新該ListPreference保存的值
mEditor.putString(mKey, mEntryValues[fpos].toString());
mEditor.commit();
// 取消ListPreference設置對話框
getDialog().dismiss();
}
});
return convertView;
}
// ListPreference每一項對應的Layout文件的結構體
private final class ViewHolder {
ImageView img;
TextView info;
RadioButton check;
LinearLayout layout;
}
}
說明:彈出的列表對話框中的每一項的內容是通過布局icon_adapter.xml來顯示的。下面看看icon_adapter.xml的源碼。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/icon_layout" android:orientation="horizontal" android:paddingLeft="6dp" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/icon_img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_vertical" android:layout_margin="4dp"/> <TextView android:id="@+id/icon_info" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:paddingLeft="6dp" android:layout_gravity="left|center_vertical" android:textAppearance="?android:attr/textAppearanceLarge" /> <RadioButton android:id="@+id/icon_check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="false" android:layout_gravity="right|center_vertical" android:layout_marginRight="6dp"/> </LinearLayout>
至此,自定義的ListPreference就算完成了。下面就是如何使用它了。
3. 使用該自定義ListPreference
我們是通過PreferenceFragment使用該自定義的ListPreference。
3.1 PreferenceFragment的配置文件
res/xml/preferences.xml的內容如下:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" xmlns:iconlistpreference="http://schemas.android.com/apk/res/com.skw.fragmenttest"> <!-- 系統默認的ListPreference --> <PreferenceCategory android:title="PreferenceCategory A"> <!-- (01) android:key是Preferece的id (02) android:title是Preferece的大標題 (03) android:summary是Preferece的小標題 (04) android:dialogTitle是對話框的標題 (05) android:defaultValue是默認值 (06) android:entries是列表中各項的說明 (07) android:entryValues是列表中各項的值 --> <ListPreference android:key="list_preference" android:dialogTitle="Choose font" android:entries="@array/pref_font_types" android:entryValues="@array/pref_font_types_values" android:summary="sans" android:title="Font" android:defaultValue="sans"/> </PreferenceCategory> <!-- 自定義的ListPreference --> <PreferenceCategory android:title="PreferenceCategory B"> <!-- iconlistpreference:entryIcons是自定義的屬性 --> <com.skw.fragmenttest.IconListPreference android:key="icon_list_preference" android:dialogTitle="ChooseIcon" android:entries="@array/android_versions" android:entryValues="@array/android_version_values" iconlistpreference:entryIcons="@array/android_version_icons" android:icon="@drawable/cupcake" android:summary="summary_icon_list_preference" android:title="title_icon_list_preference" /> </PreferenceCategory> </PreferenceScreen>
說明:該配置文件中使用了"系統默認的ListPreference"和"自定義的ListPreference(即IconListPreference)"。
注意,IconListPreference中的"iconlistpreference:entryIcons"屬性。前面的"iconlistpreference"與該文件的命名空間表示"xmlns:iconlistpreference="http://schemas.android.com/apk/res/com.skw.fragmenttest"中的iconlistpreference一樣! 而entryIcons則是我們自定義的屬性名稱。
3.2 自定義PreferenceFragment的代碼
public class PrefsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
...
}
4. 使用PrefsFragment
下面,就可以在Activity中使用該PrefsFragment了。
4.1 使用PrefsFragment的Activity的代碼
public class FragmentTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 獲取FragmentManager
FragmentManager fragmentManager = getFragmentManager();
// 獲取FragmentTransaction
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
PrefsFragment fragment = new PrefsFragment();
// 將fragment添加到容器frag_example中
fragmentTransaction.add(R.id.prefs, fragment);
fragmentTransaction.commit();
}
}
4.2 使用PrefsFragment的Activity的配置文件
res/layout/main.xml的內容如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <FrameLayout android:id="@+id/prefs" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
android RadioGroup實現單選以及默認選中
本文將通過radiogroup和radiobutton實現組內信息的單選, 其中radiogroup就是將radiobutton進行分組,同一管理和控制 同時實現默認選
Android開發之BroadcastReceiver詳解
BroadcastReceiver,顧名思義就是“廣播接收者”的意思,它是Android四大基本組件之一,這種組件本質上是一種全局的監聽器,用於監聽系統全局的廣播消息。它
Android使用ImageView實現支持手勢縮放效果
TouchImageView繼承自ImageView具有ImageView的所有功能;除此之外,還有縮放、拖拽、雙擊放大等功能,支持viewpager和scaletype
Android開發本地及網絡Mp3音樂播放器(八)狀態存取與界面滑動
實現功能:退出應用時,保存歌曲位置(也就是當前是第幾首歌曲)退出應用時,保存播放模式(也就是用戶設置的是順序播放/隨機播放/單曲循環)進入應用時,讀取歌曲位置進入應用時,