使用Eclipse ADT中的模板SettingsActivity切换到Tablet支持和片段

时间:2013-02-16 19:34:05

标签: java android

我从Eclipse和ADT的默认模板SettingsActivity生成了以下代码。我发现它太复杂了。我自己也加了一些。我该如何改进结构?

  1. 目前,Activity侦听器和片段侦听器 - >更好的方式?

  2. 摆脱静态偏好proxyEmail = null; - >怎么样?静态可以吗?

  3. 如何在onPreferenceChange()方法(第123行)中调用/使用findPreference(getText(R.string.key_proxy_email))?

  4. 重构想法?

    package com.xyz.abc;
    
    import java.util.List;
    
    import android.annotation.TargetApi;
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
    import android.content.res.Configuration;
    import android.os.Build;
    import android.os.Bundle;
    import android.preference.CheckBoxPreference;
    import android.preference.ListPreference;
    import android.preference.Preference;
    import android.preference.PreferenceActivity;
    import android.preference.PreferenceCategory;
    import android.preference.PreferenceFragment;
    import android.preference.PreferenceManager;
    import android.widget.Toast;
    
    public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
    
        private static final boolean ALWAYS_SIMPLE_PREFS = false;
    
        @Override
        protected void onPostCreate(Bundle savedInstanceState) {
            super.onPostCreate(savedInstanceState);
    
            setupSimplePreferencesScreen();
    
            // TODO Not used at the moment
            //final SharedPreferences sp = new SecureSharedPreferences(this, this.getSharedPreferences(MY_PREFS_FILE_NAME, Context.MODE_PRIVATE) );
    
            SharedPreferences settings = getSharedPreferences(Global.PREFERENCES, 0);
            boolean sent = settings.getBoolean(Global.PREF_SETTING_SENT, false);
            if (sent) {
                Toast.makeText(getApplicationContext(), Global.TOAST_MSG_SENT, Toast.LENGTH_LONG);
            } else {
                Toast.makeText(getApplicationContext(), Global.TOAST_MSG_ERROR, Toast.LENGTH_LONG);
            }
    
        }
    
        private void setupSimplePreferencesScreen() {
            if (!isSimplePreferences(this)) {
                return;
            }
    
            addPreferencesFromResource(R.xml.pref_dummy);   // Be able to display first title
            PreferenceCategory fakeHeader = new PreferenceCategory(this);       
            fakeHeader.setTitle(R.string.pref_header_settings);     
            getPreferenceScreen().addPreference(fakeHeader);
            addPreferencesFromResource(R.xml.pref_settings);
    
            fakeHeader = new PreferenceCategory(this);  
            fakeHeader.setTitle(R.string.pref_header_advanced);
            getPreferenceScreen().addPreference(fakeHeader);
            addPreferencesFromResource(R.xml.pref_advanced);
    
            fakeHeader = new PreferenceCategory(this);  
            fakeHeader.setTitle(R.string.pref_header_general);
            getPreferenceScreen().addPreference(fakeHeader);
            addPreferencesFromResource(R.xml.pref_general);
    
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
            sp.registerOnSharedPreferenceChangeListener(this);
    
            toggleProxyEmail(findPreference(getText(R.string.key_via)), findPreference(getText(R.string.key_proxy_email)));
        }
    
        /** {@inheritDoc} */
        @Override
        public boolean onIsMultiPane() {
            return isXLargeTablet(this) && !isSimplePreferences(this);
        }
    
        /**
         * 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;
        }
    
        private static boolean isSimplePreferences(Context context) {
            return ALWAYS_SIMPLE_PREFS || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB || !isXLargeTablet(context);
        }
    
        /** {@inheritDoc} */
        @Override
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        public void onBuildHeaders(List<Header> target) {
            if (!isSimplePreferences(this)) {
                loadHeadersFromResource(R.xml.pref_headers, target);
            }
        }
    
        private static Preference.OnPreferenceChangeListener bindPrefSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object value) {
                String stringValue = value.toString();
    
                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.
                    preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
    
                } else {
                    // For all other preferences, set the summary to the value's simple string representation.
                    preference.setSummary(stringValue);
                }
                return true;
            } 
    
        };
    
        private static Preference.OnPreferenceChangeListener bindPrefKeyToEditTextListener = new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object value) {    
                ((CheckBoxPreference) preference).setChecked((Boolean) value);
                toggleProxyEmail(preference, SettingsPreferenceFragment.proxyEmail);
    
                return true;
            }
    
        };
    
        private static void bindPreferenceSummaryToValue(Preference preference) {
            preference.setOnPreferenceChangeListener(bindPrefSummaryToValueListener);
    
            // Trigger the listener immediately with the preference's current value.
            bindPrefSummaryToValueListener.onPreferenceChange(preference, PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(), ""));
        }
    
        private static void bindPreferenceKeyToEditText(Preference preference) {
            preference.setOnPreferenceChangeListener(bindPrefKeyToEditTextListener);
    
            // Trigger the listener immediately with the preference's current value.
            bindPrefKeyToEditTextListener.onPreferenceChange(preference, PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getBoolean(preference.getKey(), false));
        } 
    
    
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        public static class SettingsPreferenceFragment extends PreferenceFragment {
    
            static Preference proxyEmail = null;
    
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                addPreferencesFromResource(R.xml.pref_settings);
    
                proxyEmail = findPreference(getText(R.string.key_proxy_email));
                toggleProxyEmail(findPreference(getText(R.string.key_via)), proxyEmail);
    
                bindPreferenceSummaryToValue(findPreference(getText(R.string.key_dest_email)));
                bindPreferenceKeyToEditText(findPreference(getText(R.string.key_via)));
                bindPreferenceSummaryToValue(findPreference(getText(R.string.key_proxy_email)));
                bindPreferenceSummaryToValue(findPreference(getText(R.string.key_pwd)));
                bindPreferenceSummaryToValue(findPreference(getText(R.string.key_provider)));
            } 
        }
    
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        public static class AdvancedPreferenceFragment extends PreferenceFragment {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                addPreferencesFromResource(R.xml.pref_advanced);
            }
        }
    
        @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);
    
                bindPreferenceSummaryToValue(findPreference(getText(R.string.key_help)));
            }
        }
    
        private static void toggleProxyEmail(Preference prefKey, Preference prefValue) {
            if (prefKey instanceof CheckBoxPreference) {
                if(((CheckBoxPreference) prefKey).isChecked()) {
                    prefValue.setEnabled(true);
                } else {
                    prefValue.setEnabled(false);
                }
            }
        }
    
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {    // Only called in a normal Activity
            if(key.equals(findPreference(getString(R.string.key_via)).getKey())) {
                toggleProxyEmail(findPreference(getText(R.string.key_via)), findPreference(getText(R.string.key_proxy_email)));
            }
        }
    
    }
    

0 个答案:

没有答案