如何在我的应用程序上处理此用户首选项更改?

时间:2019-08-05 11:55:17

标签: android-studio android-fragments sharedpreferences

在我的Android应用程序上,我想处理用户在首选项上的选择。

因此,我有一个显示温度值(例如0°C)的文本视图和一个“首选项”菜单。当用户输入“首选项”时,他具有一个ListPreference,可以从中选择单位是摄氏度还是华氏度。如果他更改单位,则当他返回时,“文本视图”应反映该更改(例如,他选择了华氏温度,因此现在“文本视图”显示32°F)。

MainActivity.java

public class MainActivity extends AppCompatActivity {
    // Temperature Variables
    private float temperature;
    private String current_unit;

    // Interface Objects
    private TextView txt_temp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set ActionBar to Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Get view objects
        txt_temp = findViewById(R.id.temperature);

        // Sets default preference values only once, first time this is called.
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

        // Getting current preferences
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        current_unit = prefs.getString("temperature_option", "celsius");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

SettingsActivity.java

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        // Enable the Toolbar Up button
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if(getSupportActionBar() != null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.settings, new SettingsFragment())
                .commit();
    }
}

SettingsFragment.java

public class SettingsFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener {
    private ListPreference listPref_temperature_unit;

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preferences, rootKey);

        listPref_temperature_unit = findPreference("temperatureUnit");

    }

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        // Control if selected options are correct and update each summary
        // for example: number of selections in MultiSelectListPreference
        String key = preference.getKey();

        switch (key) {
            case "temperatureUnit":
                setTemperatureUnitSummary(newValue.toString());

                return true;
        }

        return false;
    }

    @Override
    public void onResume() {
        // Register listeners and make sure every preference has it's current selected entry in summary
        super.onResume();

        listPref_temperature_unit.setOnPreferenceChangeListener(this);
/*
        listPref_temperature_unit.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener( ) {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                // Control if selected options are correct and update each summary
                // for example: number of selections in MultiSelectListPreference
                String key = preference.getKey();

                if ("temperatureUnit".equals(key)) {
                    //listPref_temperature_unit.setSummary(newValue.toString());
                    setTemperatureUnitSummary(newValue.toString());
                }
                return true;
            }
        });
*/
        setTemperatureUnitSummary(null);
    }

    @Override
    public void onPause() {
        // Unregister listeners
        super.onPause();

        listPref_temperature_unit.setOnPreferenceChangeListener(null);
    }

    private void setTemperatureUnitSummary(String newValue) {
        // Set Temperature Unit Summary to show it's current value
        String setTo = newValue;
        if(setTo == null) setTo = listPref_temperature_unit.getValue();
        String[] optionEntries = this.getResources().getStringArray(R.array.tempUnit_entries);
        try {
            // Within a PreferenceFragment, it's much easier to lookup the display text.
            // The findIndexOfValue() method is very handy when you have access to the Preference.
            listPref_temperature_unit.setSummary("Currently set to " +
                    optionEntries[listPref_temperature_unit.findIndexOfValue(setTo)]);
        }
        catch(Exception e) {
            listPref_temperature_unit.setSummary("Preference error: unknown value of listPref: " + setTo);
        }
    }
}

我应该在每个onCreate或onStart中检查首选项是否更改吗?也许与听众?我不知道该怎么做。

谢谢

0 个答案:

没有答案