Using Entries from the Settings Activity

Viewed 38

I'm still relatively new to Android development, so please don't hold it against me. My problem is that I have created a preference activity for my program, but don't know how to access it so that the other activity uses/stores these values from startup. Furthermore, in the default settings activity, I don't have a toolbar with an arrow that takes me back to the first activity. I've tried a lot on the back arrow, but somehow nothing helped. Thank you very much.

Settings-Activity:

public class SettingsActivity extends AppCompatActivity {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.settings_activity);
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.settings, new SettingsFragment())
            .commit();


    ActionBar actionBar = getSupportActionBar();

    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

}

public static class SettingsFragment extends PreferenceFragmentCompat {
    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.root_preferences, rootKey);
    }
}

}

Settings-Activity

1 Answers

First add an empty constructor to your fragment:

public SettingsFragment() {
}

Your setting activity need to start listening for changes:

@Override
public void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener( this );
}

@Override
public void onPause() {
    super.onPause();
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}

You can also call onSharedPreferenceChanged that functions as a listener on your preferences:

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if( key.equalsIgnoreCase( "key1") ) {
        // example use
        ListPreference lp = (ListPreference) findPreference( key );
        lp.setTitle( lp.getEntry() );
        SettingsActivity.FONT_STYLE = lp.getValue();
    }
    else if( key.equalsIgnoreCase( "key2") ) {
        // example use
        ListPreference lp = (ListPreference) findPreference( key );
        lp.setTitle( lp.getEntry() );
        SettingsActivity.FONT_SIZE = lp.getValue();
    }
}
Related