I am new to creating PreferenceActivity. My question is how to enable and disable option in preference screen by changing other preference?
My prefs.xml:
<ListPreference
android:entries="#array/units"
android:entryValues="#array/lunits"
android:key="listUnits"
android:summary="Units schosssing"
android:title="Units" android:defaultValue="C"/>
<ListPreference
android:entries="#array/palette"
android:entryValues="#array/lpalette"
android:key="listpalette"
android:summary="Palette schosssing"
android:title="Palette"
android:defaultValue="1"/>
In the listUnits there are 2 options, Celsius and Fahrenheit, so if user selects Celsius the listpalette should get enabled, and if user selects Fahrenheit becomes disabled, how can I do this?
My settings activity:
public class SettingsActivity extends PreferenceActivity
{
#Override
protected void onCreate(final 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(final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
}
This code may be useful to you. Can take as reference.
First take instance of both of the ListPreference and apply this method.
ListPreference mlistUnits, mlistPalette;
mlistUnits= (ListPreference)findPreference("listUnits");
mlistPalette= (ListPreference)findPreference("listpalette");
mlistUnits.setEnable(false);
mlistPalette.setEnabled(true);
and use below listner
OnPreferenceChangeListener listener = new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// newValue is the value you choose
return false;
}
};
apply listener to ListPreference
mlistPalette.setOnPreferenceChangeListener(listener);
Firstly you can set default value for your listUnits listpreference to celcius or Fahrenheit ,according this you can make enable-disable your second listpreference.
Now when changing your Preference by selecting anyone of them you can follow below procedure.
1) implement OnSharedPreferenceChangeListener in your MyPreferenceFragment class and override the method onSharedPreferenceChanged
2) Code like below in your method
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
// TODO Auto-generated method stub
if (key.equals("listUnits")) {
final String value = sharedPreferences.getString(key, "");
Preference Pref_cec=findPreference("listpalette");
if (value.equals("celcius")) {
wallpaperPref_admin.setEnabled(true);
}else{
wallpaperPref_admin.setEnabled(false);
}
}
}
Hope it will Help. Let me know if anything missing in my post.
As your second list is evaluated on basic of first list, what you may do
Look for preference click on the First list, get the value of preference clicked.
Using this value simply enable/disable your second list.
Related
I am trying to open the android default TTS settings whenever I click on the particular preference in my App settings. My pref_settings.xml looks like this:
<PreferenceScreen
android:key="Lang_Select"
android:title="Language"
android:summary="Select a Language">
</PreferenceScreen>
This is my list in android settings. and my SettingsActivity.java looks like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
public static class ChatSettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.pref_settings);
}
}
#Override
public void onBackPressed() {
super.finish();
}
}
How can I start the android default TTS settings whenever the language button is clicked?
Thanks.
I have not worked with PreferenceFragmentCombat only with normal PreferenceFragment, but I guess it´s not that much difference in the basic implementations. So please, be noticed that this is maybe not the answer for your problem, but I try to help you a little bit and have to show some code. I have done it in my onCreate() method like this:
public class PreferenceFragment extends android.preference.PreferenceFragment {
private Preference mYourPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference_layout);
//initialize your preference with the key you used in xml layout
mYourPreference=(Preference)getPreferenceManager().findPreference(yourPreferenceKey);
//set on click listener
mYourPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
//start the activity
startActivity(new Intent(android.provider.Settings.ACTION_VOICE_INPUT_SETTINGS), 0);
return true;
}
});
}
}
I don´t know if ACTION_VOICE_INPUT_SETTINGS will work, just try it.
Try this:
startActivity(Intent("com.android.settings.TTS_SETTINGS"))
See: https://cs.android.com/android/platform/superproject/+/master:cts/apps/CtsVerifier/src/com/android/cts/verifier/speech/tts/TtsTestActivity.java;l=21?q=TTS_SETTINGS
I am implementing the Settings for my android app through the PreferenceFragment.
My android:summary for the different Preferences should display the current value at all times therefore I have read through severals posts and the official documentation.
Although I got it working technically my solution seems kind of hacky and I am now searching for best practice since I found no good source on how it is meant to be properly implemented.
For example I implemented onSharedPreferenceChanged to listen for changes and to update the UI, but after every restart of the PreferenceFragment, the initial android:summary is shown again. To solve this I added this to the onCreate
// display current value in the UI
EditTextPreference editText = (EditTextPreference) findPreference("serverAddress");
editText.setSummary(editText.getText());
Is this is how it is supposed to be done or am I misunderstanding something ?
Full Code:
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SERVER_ADDRESS = "serverAddress";
public static final String KEY_PREF_GENDER = "gender";
public SettingsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
//Load the preferences from the XML file
addPreferencesFromResource(R.xml.preferences);
// display current value in the UI
EditTextPreference editText = (EditTextPreference) findPreference("serverAddress");
editText.setSummary(editText.getText());
}
// Listen for settings changes and update the UI
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(KEY_PREF_SERVER_ADDRESS)) {
Preference serverAddressPref = findPreference(key);
//Set UI to display updated summary
serverAddressPref.setSummary(sharedPreferences.getString(key, ""));
}
if (key.equals(KEY_PREF_GENDER)) {
Preference serverAddressPref = findPreference(key);
//Set UI to display updated summary
serverAddressPref.setSummary(sharedPreferences.getString(key, ""));
}
}
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
}
So I am trying to implement a preferences menu in my app. I used the standard generated template in android studio. THe issue is that now I can't figure out how save the values the user specifies. I thought about using a click listener to determine when a user clicked a checkbox and then getting the actual value of the checkbox and saving that to sharedpreferences, but I can't figure out how to do it.
Does anyone have any suggestions on how use onClick in a preference activity?
OK, we seem to be on the right track about the system storing the values automatically, but whenever I try to reference them from my main class, it always returns null. Here is my code:
boolean trueorfalse = PreferenceManager.getDefaultSharedPreferences(getActivity())
.getBoolean("my_key", false)
;
So I assume you've already defined your Preferences in res --> xml and it looks something like this:
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="my_key"
android:summary="#string/desc_string"
android:title="#string/title_string" />
</PreferenceScreen>
As soon as the user checks or unchecks the CheckBox the systen will automatically create an entry in the default Preference-file which you can access like this:
PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean("my_key", false);
But back to your initial question: If you want to assign an onClick-Listener to your preference you have to do something like this:
Preference myPreference = (Preference) findPreference("my_key");
myPreference .setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
// do something
}
});
Note: In this example it isn't a CheckBoxPreference, it's just a simple Preference
I tried the same in my SettingsMenu by implementing OnSharedPreferenceChangeListener
public class SettingsMenu extends PreferenceActivity implements OnSharedPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
Context context = getApplicationContext();
SharedPreferences menu_settings = PreferenceManager.getDefaultSharedPreferences(context);
menu_settings.registerOnSharedPreferenceChangeListener(this);
...
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// check the checkboxes
}
}
Hope it helps :)
I'm trying to prevent the user from entering an empty string into an EditTextPreference (in the example, catName). I use a OnPreferenceChangeListener to detect when a change is made to the EditTextPreference, and if there is a change and the string is blank, I use the EditTextPreference.setText() command to reset to the old value. However, the new value doesn't show up properly if I reopen the EditTextPreference in the GUI (the string is blank), and if I go back into the main app, I can verify that a blank value is being saved to the preferences.
I've verified that the if statement executes as expected, and that my parameter keeping track of the old name (oldCatName) is updating as expected. I can even log the catName.getText() value right before the setOnPreferenceChangeListener finishes execution and I always see the value I expect (the new value set by the user, and when they enter a blank value, it properly resets to the old value). I'm not sure why setting the value to the EditTextPreference isn't saving the value to the preferences file or updating the GUI.
public class SettingsActivity extends PreferenceActivity {
private String oldCatName;
private EditTextPreference catName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
catName = (EditTextPreference) findPreference("cat_name");
oldCatName = catName.getText();
catName.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newVal) {
final String value = (String) newVal;
if (value.equals("")) {
catName.setText(oldCatName);
Log.e("new value", catName.getText());
}
else
oldCatName = value;
return true;
}
});
}
}
Thanks for the help!
-Michael
Edit: A clarification. The logic in the if statement is executing correctly. The string value of the EditTextPreference is even updating correctly. However, the value in the GUI if the user taps on the EditTextPreference again does not correctly update, and the value in the app's shared preferences does not update correctly. It stays blank.
Finally found a solution by doing the following:
I used a SharedPreferences.OnSharedPreferenceChangeListener instead of a Preference.OnPreferenceChangeListener. The Preference.OnPreferenceChangeListener looks for when the user changes a preference through the settings menu, and behaves before the change is committed to the preference data. The SharedPreferences.OnSharedPreferenceChangeListener listens for changes to the actual preference data, not changes in the GUI, so it happens a little later. I noticed that in my first attempt, I could run setText() immediately followed by getText() on my EditTextPreference object, and the getText() value wouldn't match what I had just set the setText() value to. I'm not sure why this happens, but waiting for the changes to actually commit before trying to run setText() led to the correct response. Maybe it was a timing issue?
I run setPreferenceScreen(null) and addPreferencesFromResource(R.xml.settings) after updating the value in the EditTextPreference. If I didn't do this, sometimes when the user would click on the EditTextPreference again, the value in the field would appear blank even though the value in the settings file wasn't. This forces the settings page to, more or less, refresh itself.
The working code is below:
public class SettingsActivity extends PreferenceActivity {
private String oldCatName;
private EditTextPreference catName;
private SharedPreferences.OnSharedPreferenceChangeListener listener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
createListener();
catName = (EditTextPreference) findPreference("cat_name");
oldCatName = catName.getText();
}
private void createListener() {
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
String value = sharedPreferences.getString("cat_name", "NULL");
if (value.equals("")) {
catName.setText(oldCatName);
setPreferenceScreen(null);
addPreferencesFromResource(R.xml.settings);
} else {
oldCatName = value;
}
}
};
PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.registerOnSharedPreferenceChangeListener(listener);
}
}
~9 yrs late, Hope this helps some one else.
I too faced similar issue. It can be done simply by returning false. As the documentation states returning true will update the value and you want to ignore changes.
catName.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newVal) {
final String value = (String) newVal;
if (value.equals("")) {
catName.setText(oldCatName);
Log.e("new value", catName.getText());
return false ; // <----------------------------------
}
else
oldCatName = value;
return true;
}
});
In Android 4, I have a preference value that I want to appear in the standard form E2C56DB5-DFFB-48D2-B060-D0F5A71096E0. But the user may enter the value without dashes. I would like to allow the user to enter it with any combination of whitespace or dashes, and simply have my code normalize it.
I am using the code below, and I see the log line, but it does nothing. I am guessing this is because Android has another Editor object open that overwrites my changes. Is there any other way to accomplish this?
public class UuidFragment extends PreferenceFragment {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
this.getPreferenceScreen().findPreference("pref_uuid").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.toString().length() != 0) {
String normalizedUuid=normalizeUuid(newValue.toString());
// TODO: this code runs but does nothing, I think because after committing the change, there is a higher level editor that commits the old value
// thereby undoing this change
if (!normalizedUuid.equals(newValue.toString())) {
Log.d(TAG, "Adjusting uuid from "+newValue.toString()+" to "+normalizedUuid);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(UuidFragment.this.getActivity());
SharedPreferences.Editor editor = settings.edit();
editor.putString(preference.getKey(), normalizedUuid);
editor.commit();
}
return true;
}
}
});
}
}
Try subclassing EditTextPreference and overriding setText(). In your setText() method, fix up the passed-in string before chaining to the superclass. Then, reference your EditTextPreference subclass from your preference XML.