1. 程式人生 > >學習Android Studio開發工具之Activity3(框架3)

學習Android Studio開發工具之Activity3(框架3)

接上文學習Android Studio開發工具之Activity3(框架2)
本篇介紹Android Studio提供的使用者偏好設定,新建一個Module命名為Prefs,選擇Settings Activity,如圖:
這裡寫圖片描述
執行的效果如圖:
這裡寫圖片描述
SettingsActivity繼承自AppCompatPreferenceActivity間接繼承自PreferenceActivity,覆寫方法onBuildHeaders(List<Header> target),在其方法內部載入檢視資原始檔 loadHeadersFromResource(R.xml.pref_headers, target);


所以這裡的載入的檢視資源是preference-headers、PreferenceScreen、ListPreference、Preference、EditTextPreference、SwitchPreference、RingtonePreference等標籤的xml檔案。
對於繼承自Preference的屬性配置,都會以指定key和輸入選擇值value的map形式,sharedpredference的方式儲存在手機記憶體data/data/<程式包名>.程式名/shared_prefs/<包名>.prefs_preferences.xml
主設定介面的xml檔案為:pref_headers.xml

<preference-headers xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- These settings headers are only used on tablets. -->

    <header
        android:fragment="com.hitsz.xiaokai.prefs.SettingsActivity$GeneralPreferenceFragment"
        android:icon="@drawable/ic_info_black_24dp"
android:title="@string/pref_header_general"/>
<header android:fragment="com.hitsz.xiaokai.prefs.SettingsActivity$NotificationPreferenceFragment" android:icon="@drawable/ic_notifications_black_24dp" android:title="@string/pref_header_notifications"/> <header android:fragment="com.hitsz.xiaokai.prefs.SettingsActivity$DataSyncPreferenceFragment" android:icon="@drawable/ic_sync_black_24dp" android:title="@string/pref_header_data_sync"/> </preference-headers>

主設定介面的標籤使用preference-headers,header在header中可以設定顯示的fragment,圖示和標題等內容。
再開這三個設定選項分別對應的檢視檔案
第一個是通用設定pref_general.xml
這裡寫圖片描述

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <SwitchPreference
        android:defaultValue="true"
        android:key="example_switch"
        android:summary="@string/pref_description_social_recommendations"
        android:title="@string/pref_title_social_recommendations"/>

    <!-- NOTE: EditTextPreference accepts EditText attributes. -->
    <!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
    <EditTextPreference
        android:capitalize="words"
        android:defaultValue="@string/pref_default_display_name"
        android:inputType="textCapWords"
        android:key="example_text"
        android:maxLines="1"
        android:selectAllOnFocus="true"
        android:singleLine="true"
        android:title="@string/pref_title_display_name"/>

    <!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog to
         dismiss it. -->
    <!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
    <ListPreference
        android:defaultValue="-1"
        android:entries="@array/pref_example_list_titles"
        android:entryValues="@array/pref_example_list_values"
        android:key="example_list"
        android:negativeButtonText="@null"
        android:positiveButtonText="@null"
        android:title="@string/pref_title_add_friends_to_messages"/>

</PreferenceScreen>

通用設定是主設定檔案preference-headers包含的三個Fragment載入的檢視檔案之一,包含三個組合控制元件(也是系統帶的),分別是SwitchPreference、EditTextPreference、ListPreference,同樣有很多屬性何以設定,其中ListPreference需要載入對話方塊listview陣列資料,分別是title和對應的value,用於分類處理不同的邏輯。

  <!-- Example General settings -->
    <string name="pref_header_general">General</string>

    <string name="pref_title_social_recommendations">Enable social recommendations</string>
    <string name="pref_description_social_recommendations">Recommendations for people to contact
        based on your message history
    </string>

    <string name="pref_title_display_name">Display name</string>
    <string name="pref_default_display_name">John Smith</string>

    <string name="pref_title_add_friends_to_messages">Add friends to messages</string>
    <string-array name="pref_example_list_titles">
        <item>Always</item>
        <item>When possible</item>
        <item>Never</item>
    </string-array>
    <string-array name="pref_example_list_values">
        <item>1</item>
        <item>0</item>
        <item>-1</item>
    </string-array>

效果圖如下:
這裡寫圖片描述
EditTextPreference也有一個點選顯示編輯對話方塊的效果,可以設定預設顯示的資料,以及設定輸入資料的型別,和儲存的key,這裡的key為example_text,對應的value為輸入的資料。效果如圖:
這裡寫圖片描述
這裡寫圖片描述
對於SwitchPreference,他是採用sharedprefrence儲存boolean型別資料。

再來看通知設定檢視資原始檔pref_notification.xml
這裡寫圖片描述

這裡設定的是新message到來時的鈴聲和震動效果,有一個SwitchPreference控制總的開關,下面兩個分別是RingtonePreference,選擇系統鈴聲的preference,而控制震動效果的也是一個SwitchPreference的開關。

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- A 'parent' preference, which enables/disables child preferences (below)
         when checked/unchecked. -->
    <SwitchPreference
        android:defaultValue="true"
        android:key="notifications_new_message"
        android:title="@string/pref_title_new_message_notifications"/>

    <!-- Allows the user to choose a ringtone in the 'notification' category. -->
    <!-- NOTE: This preference will be enabled only when the checkbox above is checked. -->
    <!-- NOTE: RingtonePreference's summary should be set to its value by the activity code. -->
    <RingtonePreference
        android:defaultValue="content://settings/system/notification_sound"
        android:dependency="notifications_new_message"
        android:key="notifications_new_message_ringtone"
        android:ringtoneType="notification"
        android:title="@string/pref_title_ringtone"/>

    <!-- NOTE: This preference will be enabled only when the checkbox above is checked. -->
    <SwitchPreference
        android:defaultValue="true"
        android:dependency="notifications_new_message"
        android:key="notifications_new_message_vibrate"
        android:title="@string/pref_title_vibrate"/>

</PreferenceScreen>
  <!-- Example settings for Notifications -->
    <string name="pref_header_notifications">Notifications</string>

    <string name="pref_title_new_message_notifications">New message notifications</string>

    <string name="pref_title_ringtone">Ringtone</string>
    <string name="pref_ringtone_silent">Silent</string>

    <string name="pref_title_vibrate">Vibrate</string>

還有一個數據同步設定檢視資原始檔pref_data_sync.xml
這裡寫圖片描述

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

<!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog to
     dismiss it. -->
<!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
<ListPreference
    android:defaultValue="180"
    android:entries="@array/pref_sync_frequency_titles"
    android:entryValues="@array/pref_sync_frequency_values"
    android:key="sync_frequency"
    android:negativeButtonText="@null"
    android:positiveButtonText="@null"
    android:title="@string/pref_title_sync_frequency"/>

<!-- This preference simply launches an intent when selected. Use this UI sparingly, per
     design guidelines. -->
<Preference android:title="@string/pref_title_system_sync_settings">
    <intent android:action="android.settings.SYNC_SETTINGS"/>
</Preference>

</PreferenceScreen>

包含兩個控制元件,一個是選擇同步頻率的ListPreference,一個是同步模式的選擇。

   <!-- Example settings for Data & Sync -->
    <string name="pref_header_data_sync">Data &amp; sync</string>

    <string name="pref_title_sync_frequency">Sync frequency</string>
    <string-array name="pref_sync_frequency_titles">
        <item>15 minutes</item>
        <item>30 minutes</item>
        <item>1 hour</item>
        <item>3 hours</item>
        <item>6 hours</item>
        <item>Never</item>
    </string-array>
    <string-array name="pref_sync_frequency_values">
        <item>15</item>
        <item>30</item>
        <item>60</item>
        <item>180</item>
        <item>360</item>
        <item>-1</item>
    </string-array>

    <string name="pref_title_system_sync_settings">System sync settings</string>

這裡寫圖片描述

這裡寫圖片描述
當所有的設定選項都設定完成後,再點到pc終端開啟虛擬機器控制終端,adb shell,進入data/data/<程式包名>.程式名/shared_prefs/ 資料夾下,使用cat命令檢視儲存的xml檔案
這裡寫圖片描述

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <boolean name="notifications_new_message" value="true" />
    <string name="notifications_new_message_ringtone">content://settings/system/
notification_sound</string>
    <string name="sync_frequency">180</string>
    <boolean name="notifications_new_message_vibrate" value="true" />
    <boolean name="example_switch" value="true" />
    <string name="example_text">stephenxe</string>
    <string name="example_list">-1</string>
</map>

可以看到我們做的所有設定都以鍵值對的形式儲存在本地。

接下來必然還是最重要的程式碼分析:
主程式有兩個類分別是作為父類的AppCompatPreferenceActivity 繼承自PreferenceActivity和 繼承自AppCompatPreferenceActivity的子類SettingsActivity。
AppCompatPreferenceActivity的作用是為了定製自己的SetingsActivity做了一些相容性的設定(AppCompat:經常看到,其實就是應用相容字首),其中使用了委派機制(Delegate).

package com.hitsz.xiaokai.prefs;

import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A {@link android.preference.PreferenceActivity} which implements and proxies the necessary calls
 * to be used with AppCompat.
 */
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {

    private AppCompatDelegate mDelegate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getDelegate().installViewFactory();
        getDelegate().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        getDelegate().onPostCreate(savedInstanceState);
    }

    public ActionBar getSupportActionBar() {
        return getDelegate().getSupportActionBar();
    }

    public void setSupportActionBar(@Nullable Toolbar toolbar) {
        getDelegate().setSupportActionBar(toolbar);
    }

    @Override
    public MenuInflater getMenuInflater() {
        return getDelegate().getMenuInflater();
    }

    //activity設定佈局的setContentView
    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate().setContentView(layoutResID);
    }

    @Override
    public void setContentView(View view) {
        getDelegate().setContentView(view);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().setContentView(view, params);
    }

    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().addContentView(view, params);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        getDelegate().onPostResume();
    }

    //當標題更改時回撥
    @Override
    protected void onTitleChanged(CharSequence title, int color) {
        super.onTitleChanged(title, color);
        getDelegate().setTitle(title);
    }
    //配置更改時回撥
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        getDelegate().onConfigurationChanged(newConfig);
    }

    @Override
    protected void onStop() {
        super.onStop();
        getDelegate().onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getDelegate().onDestroy();
    }

    public void OptionsMenu() {
        getDelegate().invalidateOptionsMenu();
    }
    //獲取應用相容委託,適配不同android版本
    private AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, null);
        }
        return mDelegate;
    }
}

再看SettingsActivity

package com.hitsz.xiaokai.prefs;


import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.support.v7.app.ActionBar;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;
import android.view.MenuItem;

import java.util.List;

/**
 * A {@link PreferenceActivity} that presents a set of application settings. On
 * handset devices, settings are presented as a single list. On tablets,
 * settings are split by category, with category headers shown to the left of
 * the list of settings.
 * <p/>
 * See <a href="http://developer.android.com/design/patterns/settings.html">
 * Android Design: Settings</a> for design guidelines and the <a
 * href="http://developer.android.com/guide/topics/ui/settings.html">Settings
 * API Guide</a> for more information on developing a Settings UI.
 */
public class SettingsActivity extends AppCompatPreferenceActivity {
    /**
     * A preference value change listener that updates the preference's summary
     * to reflect its new value.
     * 當設定值發生變化時監聽,使用preference.setSummary()方法更新到記憶體中,內部類的形式實現
     */
    private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String stringValue = value.toString();

    //判斷preference的型別,對於不同的型別做不同方式的儲存,需要先將資料轉化為CharSequence型別
            if (preference instanceof ListPreference) {
                // For list preferences, look up the correct display value in
                // the preference's 'entries' list.
                ListPreference listPreference = (ListPreference) preference;
                int index = listPreference.findIndexOfValue(stringValue);

                // Set the summary to reflect the new value.設定summary
                preference.setSummary(
                        index >= 0
                                ? listPreference.getEntries()[index]
                                : null);

            } else if (preference instanceof RingtonePreference) {
                // For ringtone preferences, look up the correct display value
                // using RingtoneManager.對於ringtone設定需要使用RingtoneManager設定,根據uri獲取本地Contenprovider鈴聲資料
                if (TextUtils.isEmpty(stringValue)) {
                    // Empty values correspond to 'silent' (no ringtone).
                    preference.setSummary(R.string.pref_ringtone_silent);

                } else {
                    Ringtone ringtone = RingtoneManager.getRingtone(
                            preference.getContext(), Uri.parse(stringValue));

                    if (ringtone == null) {
                        // Clear the summary if there was a lookup error.
                        preference.setSummary(null);
                    } else {
                        // Set the summary to reflect the new ringtone display
                        // name.
                        String name = ringtone.getTitle(preference.getContext());
                        preference.setSummary(name);
                    }
                }

            } else {
                // For all other preferences, set the summary to the value's
                // simple string representation.對於其他的簡單資料型別,直接設定儲存即可
                preference.setSummary(stringValue);
            }
            return true;
        }
    };

    /**
     * Helper method to determine if the device has an extra-large screen. For
     * example, 10" tablets are extra-large.判斷裝置尺寸
     */
    private static boolean isXLargeTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
    }

    /**
     * Binds a preference's summary to its value. More specifically, when the
     * preference's value is changed, its summary (line of text below the
     * preference title) is updated to reflect the value. The summary is also
     * immediately updated upon calling this method. The exact display format is
     * dependent on the type of preference.更新summary的值,當資料更新時立即回撥
     *
     * @see #sBindPreferenceSummaryToValueListener
     */
    private static void bindPreferenceSummaryToValue(Preference preference) {
        // Set the listener to watch for value changes.
        preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

        // Trigger the listener immediately with the preference's
        // current value.
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                PreferenceManager
                        .getDefaultSharedPreferences(preference.getContext())
                        .getString(preference.getKey(), ""));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupActionBar();
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    private void setupActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // Show the Up button in the action bar.
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onIsMultiPane() {
        return isXLargeTablet(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void onBuildHeaders(List<Header> target) {
        loadHeadersFromResource(R.xml.pref_headers, target);
    }

    /**
     * This method stops fragment injection in malicious applications.
     * Make sure to deny any unknown fragments here.判斷Fragment的有效性,即設定要載入的Fragment
     */
    protected boolean isValidFragment(String fragmentName) {
        return PreferenceFragment.class.getName().equals(fragmentName)
                || GeneralPreferenceFragment.class.getName().equals(fragmentName)
                || DataSyncPreferenceFragment.class.getName().equals(fragmentName)
                || NotificationPreferenceFragment.class.getName().equals(fragmentName);
    }

    /**
     * This fragment shows general preferences only. It is used when the
     * activity is showing a two-pane settings UI.內部類實現Fragment
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class GeneralPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_general);
            setHasOptionsMenu(true);

            // Bind the summaries of EditText/List/Dialog/Ringtone preferences
            // to their values. When their values change, their summaries are
            // updated to reflect the new value, per the Android Design
            // guidelines.繫結記憶體設定值
            bindPreferenceSummaryToValue(findPreference("example_text"));
            bindPreferenceSummaryToValue(findPreference("example_list"));
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * This fragment shows notification preferences only. It is used when the
     * activity is showing a two-pane settings UI.內部類實現Fragment
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class NotificationPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_notification);
            setHasOptionsMenu(true);

            // Bind the summaries of EditText/List/Dialog/Ringtone preferences
            // to their values. When their values change, their summaries are
            // updated to reflect the new value, per the Android Design
            // guidelines.
            bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }

    /**
     * This fragment shows data and sync preferences only. It is used when the
     * activity is showing a two-pane settings UI.內部類實現Fragment
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class DataSyncPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_data_sync);
            setHasOptionsMenu(true);

            // Bind the summaries of EditText/List/Dialog/Ringtone preferences
            // to their values. When their values change, their summaries are
            // updated to reflect the new value, per the Android Design
            // guidelines.
            bindPreferenceSummaryToValue(findPreference("sync_frequency"));
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
}