Android - SharedPreference仅在第二次更改MainActivity可见性

时间:2014-04-28 13:00:52

标签: android android-layout sharedpreferences onresume listpreference

我有一个PreferenceActivity我有一个ListPreference有三个选项。在我的MainActivity's xml文件(activity_main.xml)中,我将此Button中选定的ListPreference的可见性设置为VISIBLE

一切都有效,除了一个小问题。只有在我第二次更改设置屏幕中的ListPreference后,它才会在主屏幕中更改。

更清楚地说明:

  1. 应用已启动,并显示MainActivity's activity_main.xml,其中包含上次保存的偏好设置按钮VISIBLE以及其他两个GONE
  2. 我点击F2(我使用模拟器)并单击“设置”。设置菜单打开,在下拉列表中我选择了一个不同的选项。
  3. 当我回到activity_main(使用Esc作为后面)时,没有任何改变。
  4. 但是,当我再次使用F2打开设置菜单并再次更改设置,然后返回main_layout时,按钮确实发生了变化(我在步骤2中选择的设置)。
  5. 所以,我的问题是:我如何"刷新"可见性因更改后的偏好而发生变化后我的main_layout? (当我回到它时,如何立即显示对activity_main的更改。)

    我应该在@Override onResume()中添加MainActivity方法并调用某种"刷新"有?

    提前感谢您的回复。


    这是我的代码:

    MainActivity.java:

    public class MainActivity extends ActionBarActivity
    {
        ...
    
        // Public static MainActivity so we can use findViewById from MyPrefsActivity
        public static MainActivity mActivity;
    
        public static final String LIST_PREFERENCE = "prefCheckboxOption";
        public static String currentValue;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            ...
    
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            currentValue = preferences.getString(LIST_PREFERENCE, "0");
    
            setChosenPreference(Integer.valueOf(currentValue));
    
            mActivity = this;
        }
    
        public void setChosenPreference(int chosen_value){
            // First put all Visibilities on GONE
            cbButton.setVisibility(View.GONE);
            spinnerButton.setVisibility(View.GONE);
            popupButton.setVisibility(View.GONE);
    
            // Then turn the chosen on VISIBLE again
            switch(chosen_value){
                case 0: // Multi-Click CheckBox
                default:
                    cbButton.setVisibility(View.VISIBLE);
                    break;
                case 1: // Dropdown CheckBox
                    spinnerButton.setVisibility(View.VISIBLE);
                    break;
                case 2: // Pop-up CheckBox
                    popupButton.setVisibility(View.VISIBLE);
                    break;          
            }
        }
    
        ...
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            switch(id){
                case R.id.action_settings:
                    startActivity(new Intent(this, MyPrefsActivity.class));
                    return true;
            }
            return false;
        }
    }
    

    MyPrefsActivity.java:

    public class MyPrefsActivity extends PreferenceActivity
    {
        private static int prefs = R.xml.settings;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            MyPreferenceFragment pf = new MyPreferenceFragment();
            getFragmentManager().beginTransaction().replace(android.R.id.content, pf).commit();
        }
    
        public static class MyPreferenceFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener
        {       
            @Override
            public void onCreate(Bundle savedInstanceState){
                super.onCreate(savedInstanceState);
                addPreferencesFromResource(MyPrefsActivity.prefs); // outer class
                // private members seem to be visible for inner class, and
                // making it static made things so much easier
    
                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
                preferences.registerOnSharedPreferenceChangeListener(this);
    
                MainActivity.mActivity.setChosenPreference(Integer.valueOf(MainActivity.currentValue));
            }
    
            @Override
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                if(key.equals(MainActivity.LIST_PREFERENCE)){
                    ListPreference listPreference = (ListPreference) findPreference(key); // LIST_PREFERENCE
                    if(listPreference != null){
                        listPreference.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                            @Override
                            public boolean onPreferenceChange(Preference preference, Object newValue) {
                                MainActivity.currentValue = (String) newValue;
                                MainActivity.mActivity.setChosenPreference(Integer.valueOf(MainActivity.currentValue));
                                return false;
                            }
                        });
                    }
                    else
                        Log.e("MyPrefsActivity", "listPreference is null!");
                }
                else{
                    // Other settings
                }
            }
        }
    }
    

    activity_main.xml中:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/main_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:orientation="vertical"
        tools:context="com.example.testproject.MainActivity$PlaceholderFragment" >
    
        <ImageButton
            android:id="@+id/ibtnCheckbox"
            android:visibility="visible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dp"
            android:contentDescription="@string/checkbox_content_description"
            android:src="@drawable/checkbox_unchecked"
            android:background="@drawable/transparent_background" />
    
        <ImageButton
            android:id="@+id/ibtnSpinner"
            android:visibility="gone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dp"
            android:contentDescription="@string/checkbox_content_description"
            android:src="@drawable/checkbox_unchecked"
            android:background="@drawable/transparent_background" />
    
        <ImageButton
            android:id="@+id/ibtnPopup"
            android:visibility="gone"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="15dp"
            android:contentDescription="@string/checkbox_content_description"
            android:src="@drawable/checkbox_unchecked"
            android:background="@drawable/transparent_background" />
    
    </LinearLayout>
    

    的settings.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
    
        <PreferenceCategory android:title="@string/checkbox_options_title" >
            <ListPreference
                    android:key="prefCheckboxOption"
                    android:title="@string/pref_checkbox_option"
                    android:summary="@string/checkbox_options_summary"
                    android:entries="@array/checkbox_options"
                    android:entryValues="@array/checkbox_option_values" />
    
        </PreferenceCategory>
    
    </PreferenceScreen>
    

    arrays.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string-array name="checkbox_options">
            <item>CheckBox as Multi-Click</item>
            <item>CheckBox as Dropdown</item>
            <item>CheckBox as Pop-up</item>
        </string-array>
        <string-array name="checkbox_option_values">
            <item>0</item>
            <item>1</item>
            <item>2</item>
        </string-array>
    </resources>
    

    编辑:作为对他人的参考:

    MainActivity.java完全相同,但已添加的onResume()方法已发布Sir SC

    和MyPrefsActivity.java已更改为更短的版本:

    public class MyPrefsActivity extends PreferenceActivity
    {
        private static int prefs = R.xml.settings;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
        }
    
        public static class MyPreferenceFragment extends PreferenceFragment
        {       
            @Override
            public void onCreate(Bundle savedInstanceState){
                super.onCreate(savedInstanceState);
                addPreferencesFromResource(MyPrefsActivity.prefs); // outer class
                // private members seem to be visible for inner class, and
                // making it static made things so much easier
            }
        }
    }
    

1 个答案:

答案 0 :(得分:2)

在MainActivity中创建onResume()功能。

在onResume()函数中设置更改,因此当您从另一个Activity中按回时,将调用onAesume of MainActivity,并且您将在其中编写设置。

我从你的例子中了解到它应该是这样的:

@Override
protected void onResume() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    currentValue = preferences.getString(LIST_PREFERENCE, "0");
    setChosenPreference(Integer.valueOf(currentValue));
    super.onResume();
}