学习Android Studio开发工具之Activity3(框架3)

接上文学习Android Studio开发工具之Activity3(框架2)
本篇介绍Android Studio提供的用户偏好设置,新建一个Module命名为Prefs,选择Settings Activity,如图:
学习Android Studio开发工具之Activity3(框架3)_第1张图片
运行的效果如图:
学习Android Studio开发工具之Activity3(框架3)_第2张图片
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
学习Android Studio开发工具之Activity3(框架3)_第3张图片

<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>

效果图如下:
学习Android Studio开发工具之Activity3(框架3)_第4张图片
EditTextPreference也有一个点击显示编辑对话框的效果,可以设置默认显示的数据,以及设置输入数据的类型,和保存的key,这里的key为example_text,对应的value为输入的数据。效果如图:
学习Android Studio开发工具之Activity3(框架3)_第5张图片
学习Android Studio开发工具之Activity3(框架3)_第6张图片
对于SwitchPreference,他是采用sharedprefrence保存boolean类型数据。

再来看通知设置视图资源文件pref_notification.xml
学习Android Studio开发工具之Activity3(框架3)_第7张图片

这里设置的是新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
学习Android Studio开发工具之Activity3(框架3)_第8张图片

<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>

学习Android Studio开发工具之Activity3(框架3)_第9张图片

学习Android Studio开发工具之Activity3(框架3)_第10张图片
当所有的设置选项都设置完成后,再点到pc终端打开虚拟机控制终端,adb shell,进入data/data/<程序包名>.程序名/shared_prefs/ 文件夹下,使用cat命令查看存储的xml文件
学习Android Studio开发工具之Activity3(框架3)_第11张图片

<?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);
        }
    }
}

你可能感兴趣的:(android,框架,Activity,Preference,Studio)