更改首选项后Android重启片段

时间:2016-01-20 20:27:53

标签: android android-fragments sharedpreferences settings

我有一个Spinner,其中各种值更新TextView。例如,Spinner上的0(默认值)显示" - min"而12显示" 60 min"在TextView中。这个Spinner在一个Fragment里面,它位于activity_main的TabLayout里面。我有一个PreferenceFragment(在一个普通的Activity中,因为我在使用FragmentActivity时会得到工具栏重叠。可以通过菜单调用Activity。)我可以将时间单位设置为小时或分钟。在上面的示例中,设置为分钟。

当我将分钟更改为小时时,我希望TextView更改为" - hr"当我离开PreferenceFragment并返回主活动时。这仅在我重新启动应用程序时有效,但我认为应该可以在不重新启动的情况下执行此操作。这是我的代码。

MyApplication.java

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);

        super.onCreate();

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

        String time = settings.getString("TIME", "");
        if ("".equals(time)) {
            settings.edit().putString("TIME", "2").commit();
        } else if ("1".equals(time)) {
            settings.edit().putString("TIME", "1").commit();
        } else if ("2".equals(time)) {
            settings.edit().putString("TIME", "2").commit();
        }
    }
}

activity_settings.xml

<fragment
    android:id="@+id/fragment_settings"
    android:name="com.arjendejong.ovengevormdglas.SettingsFragment"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/toolbar" />

user_settings.xml

<ListPreference
    android:defaultValue="2"
    android:entries="@array/time_unit"
    android:entryValues="@array/listTimeValues"
    android:key="time_unit"
    android:title="@string/time_unit" />

SettingsFragment.java

public class SettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addPreferencesFromResource(R.xml.user_settings);

        ListPreference timeUnitPref = (ListPreference) findPreference("time_unit");
        timeUnitPref.setSummary(timeUnitPref.getEntry());

        timeUnitPref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object o) {
                preference.setSummary(o.toString());
                return true;
            }
        });

        ListPreference timeUnitPreference = (ListPreference) findPreference("time_unit");
        timeUnitPreference.setOnPreferenceChangeListener(timeUnitChangeListener);
    }

    Preference.OnPreferenceChangeListener timeUnitChangeListener = new Preference.OnPreferenceChangeListener() {

        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {

            ListPreference timeUnitPref = (ListPreference)findPreference("time_unit");
            switch (newValue.toString()) {
                case "1":
                    PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).edit().putString("TIME", "1").commit();
                    timeUnitPref.setSummary(timeUnitPref.getEntry());
                    Toast.makeText(getActivity().getBaseContext(), "UREN", Toast.LENGTH_LONG).show();
                    Log.d("DEBUG","UREN");
                    timeUnitPref.setSummary(R.string.time_hours);
                    break;
                case "2":
                    PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).edit().putString("TIME", "2").commit();
                    timeUnitPref.setSummary(timeUnitPref.getEntry());
                    Toast.makeText(getActivity().getBaseContext(), "MINUTEN", Toast.LENGTH_LONG).show();
                    Log.d("DEBUG","MINUTEN");
                    timeUnitPref.setSummary(R.string.time_minutes);
                    break;
                /*default:
                    PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).edit().putString("TIME", "2").commit();
                    timeUnitPref.setSummary(timeUnitPref.getEntry());
                    Toast.makeText(getActivity().getBaseContext(), R.string.save_language_changes, Toast.LENGTH_LONG).show();
                    timeUnitPref.setSummary(R.string.time_minutes);
                    break;*/
            }
            return true;
        }
    };
}

TabFragment

public class TabFragment2 extends Fragment {

    TextView seekBarValue,iniCoolTimeValue, secCoolTimeValue, thirdCoolTimeValue;
    Double sum;
    private SharedPreferences pref;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tab_fragment_2, container, false);

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
        String time = settings.getString("TIME", "");

        seekBarValue = (TextView)v.findViewById(R.id.seekBarValue);
        iniCoolTimeValue = (TextView)v.findViewById(R.id.iniCoolTimeValue);
        secCoolTimeValue = (TextView)v.findViewById(R.id.secCoolTimeValue);
        thirdCoolTimeValue = (TextView)v.findViewById(R.id.thirdCoolTimeValue);

        SeekBar seekBar = (SeekBar)v.findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                seekBarValue.setText(String.valueOf(progress));

                SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity().getBaseContext());
                String time = settings.getString("TIME", "");

                if (progress >= 0 && progress < 1) {
                    if(time.equals("1")) {
                        iniCoolTimeValue.setText("- hr");
                        secCoolTimeValue.setText("- hr");
                        thirdCoolTimeValue.setText("- hr");
                    } else if(time.equals("2")){
                        iniCoolTimeValue.setText("- min");
                        secCoolTimeValue.setText("- min");
                        thirdCoolTimeValue.setText("- min");
                    }
                }
                else if (progress >= 1 && progress < 13) {
                    if( time.equals("1")){
                        sum = (482.0-427.0)/55.0;
                        DecimalFormat sumResult = new DecimalFormat("0.0");
                        iniCoolTimeValue.setText(sumResult.format(sum) + " hr");

                        sum = (427.0-371.0)/99.0;
                        DecimalFormat sumResult2 = new DecimalFormat("0.0");
                        secCoolTimeValue.setText(sumResult2.format(sum) + " hr");

                        sum = (371.0-21.0)/330.0;
                        DecimalFormat sumResult3 = new DecimalFormat("0.0");
                        thirdCoolTimeValue.setText(sumResult3.format(sum) + " hr");
                    } else if(time.equals("2")){
                        sum = (482.0 - 427.0) / 55.0 * 60.0;
                        DecimalFormat sumResult = new DecimalFormat("0");
                        sumResult.setRoundingMode(RoundingMode.HALF_UP);
                        iniCoolTimeValue.setText(sumResult.format(sum) + " min");

                        sum = (427.0 - 371.0) / 99.0 * 60.0;
                        DecimalFormat sumResult2 = new DecimalFormat("0");
                        sumResult.setRoundingMode(RoundingMode.HALF_UP);
                        secCoolTimeValue.setText(sumResult2.format(sum) + " min");

                        sum = (371.0 - 21.0) / 330.0 * 60.0;
                        DecimalFormat sumResult3 = new DecimalFormat("0");
                        sumResult.setRoundingMode(RoundingMode.HALF_UP);
                        thirdCoolTimeValue.setText(sumResult3.format(sum) + " min");
                    }
                }
            }

        });

        if(time.equals("1")) {
            iniCoolTimeValue.setText("- hr");
            secCoolTimeValue.setText("- hr");
            thirdCoolTimeValue.setText("- hr");
        } else if(time.equals("2")) {
            iniCoolTimeValue.setText("- min");
            secCoolTimeValue.setText("- min");
            thirdCoolTimeValue.setText("- min");
        }

        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        registerChangeListener();
    }

    private void registerChangeListener () {
        final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());

        sp.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
            public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
                String time = sp.getString("TIME", "");
                if ("1".equals(time)) {
                    sp.edit().putString("TIME", "1").commit();
                    Log.d("TIME UNIT", time);
                } else if ("2".equals(time)) {
                    sp.edit().putString("TIME", "2").commit();
                    Log.d("TIME UNIT", time);
                }
            }
        });
    }
}

字符串

<string name="time_unit">Time unit</string>
<string-array name="time_unit">
    <item name="hours">Hours</item>
    <item name="minutes">Minutes</item>
</string-array>
<string-array name="listTimeValues">
    <item name="hours">1</item>
    <item name="minutes">2</item>
</string-array>
<string name="time_hours">Hours</string>
<string name="time_minutes">Minutes</string>

registerChangeListener();内的onResume();中的TabFragment2有效,因为当我更改设置时,我会看到Android监视器中出现的日志。

当我离开首选项并返回上一个TabFragment活动时,如何反映设置更改?

1 个答案:

答案 0 :(得分:0)

我已将此代码块从TabFragment2.java移至MainActivity.java并添加了recreate();到if语句,现在它正在工作!

@Override
public void onResume() {
    super.onResume();
    registerChangeListener();
}

private void registerChangeListener () {
    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

    sp.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            String time = sp.getString("TIME", "");
            if ("1".equals(time)) {
                sp.edit().putString("TIME", "1").commit();
                Log.d("TIME UNIT", time);
                recreate();
            } else if ("2".equals(time)) {
                sp.edit().putString("TIME", "2").commit();
                Log.d("TIME UNIT", time);
                recreate();
            }
        }
    });
}