Android Developoping,使用AppCompatPreferenceActivity扩展了SettingsActivity

时间:2017-03-18 01:31:44

标签: java android preference

想用偏好活动改变语言,但我在listpreference中遇到了一些问题,我创建了

pref_languages.xml

SELECT { 
    [Measures].[Quantity], [Measures].[Total Price]
   ,[Measures].[Contribution Margin], [Measures].[Profit Margin]
    } ON COLUMNS,
    {
     {
            parallelperiod([Dim Date].[Calender].[Year],1,[Dim Date].[Calender].[Date].[2014-11-17])
                :
            parallelperiod([Dim Date].[Calender].[Year],1,[Dim Date].[Calender].[Date].[2014-11-30])
        },

        {
            [Dim Date].[Calender].[Date].[2014-11-17]
             :
             [Dim Date].[Calender].[Date].[2014-11-30]
        }
    }
    on rows
from [DSV_FactStoreSales 1] 
Where [Dim Store2].[Store Key].&[1024]

的strings.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <ListPreference
        android:key="app_language"
        android:title="@string/pref_header_language"
        android:defaultValue="lt"
        android:entries="@array/pref_languages_titles"
        android:entryValues="@array/pref_languages_values"
        android:negativeButtonText="@null"
        android:positiveButtonText="@null"
        />

</PreferenceScreen>

SettingsActivity

<string name="pref_header_language">Language</string>
<string-array name="pref_languages_titles">
    <item name="lithuanian">Lithuanian</item>
    <item name="english">English</item>
    <item name="russian">Russian</item>
    <item name="german">German</item>
</string-array>
<string-array name="pref_languages_values">
    <item name="lithuanian">lt</item>
    <item name="english">en</item>
    <item name="russian">ru</item>
    <item name="german">ge</item>
</string-array>

我是用Java编程的新手,我看到有很多不同的例子,但这些都不起作用,当我选择新语言时,我不知道在哪里放置代码(在哪个函数中)做一些动作来改变应用程序语言。还试图在主要活动中调用函数打印出一些首选项,如果它在我点击“设置”时发生变化则显示,但没有工作:

    package com.example.user.navigationdrawer.AMANO.Settings;


    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 android.support.v4.app.NavUtils;

    import com.example.user.navigationdrawer.R;

    import java.util.List;
    import java.util.Locale;


    public class SettingsActivity extends AppCompatPreferenceActivity {

        Locale myLocale;

        private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = 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);
                    //((ListPreference) findPreference("app_language")).setValue(Locale
                     //       .getDefault().getLanguage());
                    // Set the summary to reflect the new value.
                    preference.setSummary(
                            index >= 0
                                    ? listPreference.getEntries()[index]
                                    : null);

                } else if (preference instanceof RingtonePreference) {
                    // For ringtone preferences, look up the correct display value
                    // using RingtoneManager.
                    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.
         *
         * @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);
            }
        }

        @Override
        public boolean onMenuItemSelected(int featureId, MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                if (!super.onMenuItemSelected(featureId, item)) {
                    NavUtils.navigateUpFromSameTask(this);
                }
                return true;
            }
            return super.onMenuItemSelected(featureId, item);
        }

        /**
         * {@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.
         */
        protected boolean isValidFragment(String fragmentName) {
            return PreferenceFragment.class.getName().equals(fragmentName)
                    || GeneralPreferenceFragment.class.getName().equals(fragmentName)
                    || LanguagePreferenceFragment.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.
         */
        @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 general preferences only. It is used when the
         * activity is showing a two-pane settings UI.
         */
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        public static class LanguagePreferenceFragment extends PreferenceFragment {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                addPreferencesFromResource(R.xml.pref_languages);
                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("app_language"));
            }

            @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.
         */
        @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.
         */
        @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 Studio),因为这个很复杂,无法理解它的工作原理和方式。谢谢!

0 个答案:

没有答案