EditTextPreference value only refreshed after clicking ListPreference second time - android

I've been struggling with this issue for a while now so I decided to ask here what I' m doing wrong.
First of all:
- I have a PreferenceFragment with a ListPreference on top and an EditTextPreference below
- The ListPreference is filled with Objects, the values are stored in a file and read from there (this works flawlessly)
- The EditTextPreference should display the value of the in the ListPreference chosen object. And that's the problem: after choosing the value nothing changes so I have to click the ListPreference once more and the value is set correctly. Is this a problem with my Listener?
Here's the code:
public class SettingsTestFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
private final String[] pref_key_array = {"pref_key_lp", "pref_key_et""}; // array that contains all the preference keys of changeable values
private final int numberOfEntries = pref_key_array.length;
private Preference[] pref_entries;
String[] entries = {"Value 1", "Value 2", "Value 3"};
String[] entryValues = {"0", "1", "2"};
private int position;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
final SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(getActivity());
final EditTextPreference et = (EditTextPreference) findPreference("pref_key_et");
final ListPreference lp = (ListPreference) findPreference("pref_key_lp");
prepareListPref(lp);
pref_entries = new Preference[numberOfEntries];
for(int i = 0; i < numberOfEntries; i++) {
pref_entries[i] = getPreferenceScreen().findPreference(pref_key_array[i]);
}
lp.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
position = Integer.valueOf(myPreference.getString("pref_key_lp", "0"));
et.setText(entries[position]);
return true;
}
});
Preference.OnPreferenceChangeListener changeListener = new Preference.OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
position = Integer.valueOf(myPreference.getString("pref_key_lp", "0"));
preference.setSummary(entries[position]);
return true;
}
};
lp.setOnPreferenceChangeListener(changeListener);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
updateSummary(key, pref_key_array, numberOfEntries, pref_entries);
}
#Override
public void onResume() {
super.onResume();
// Set up listener when a key changes
for(int i = 0; i < numberOfEntries; i++) {
updateSummary(pref_key_array[i], pref_key_array, numberOfEntries, pref_entries);
}
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
public void onPause() {
super.onPause();
// Unregister listener every time a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public void prepareListPref(ListPreference lp) {
lp.setEntries(entries);
lp.setEntryValues(entryValues);
lp.setDefaultValue("0");
}
public void updateSummary(String key, String[] pref_key_array, int numberOfEntries, Preference[] pref_entries) {
for(int i = 0; i < numberOfEntries; i++) {
if(key.equals(pref_key_array[i])) {
if(pref_entries[i] instanceof EditTextPreference) {
final EditTextPreference currentPreference = (EditTextPreference) pref_entries[i];
pref_entries[i].setSummary(currentPreference.getText());
} else if(pref_entries[i] instanceof ListPreference) {
final ListPreference currentPreference = (ListPreference) pref_entries[i];
pref_entries[i].setSummary(currentPreference.getEntry());
}
break;
}
}
}
}
Summarizing the code for reading from the file and writing the value to the Settings works but only after clicking the ListPreference a second time. Do you have any ideas why?
Thanks

ok, I'm not sure what you are trying to do and what is the problem, so I've made a sample, showing the next thing:
a listPreference that its default value&entry will set the title&summary of an EditTextPreference .
when choosing an item on the ListPreference, it will also update tge title&summary of the EditTextPreference according to the value&entry of the item being selected.
Not sure what to do with the EditTextPreference. This is your choice.
I still think you should consider making a custom Preference class, as you wrote that you intend to use a lot of couples of ListPreference&EditTextPreference.
BTW, code is based on an app that I've made (link here). I've made it so that it will be easy to handle multiple listPreferences easier.
Here's the code:
res/values/strings_activity_settings.xml
<resources>
<string name="pref__custom_app_theme" translatable="false">pref__custom_app_theme</string>
<string name="pref__app_theme" translatable="false">pref__app_theme</string>
<string-array name="pref__app_theme_entries">
<item>#string/cards_light</item>
<item>#string/cards_dark</item>
</string-array>
<string name="pref__app_theme__cards_ui" translatable="false">CARDS_UI</string>
<string name="pref__app_theme__cards_ui_dark" translatable="false">CARDS_UI_DARK</string>
<string name="pref__app_theme_default" translatable="false">#string/pref__app_theme__cards_ui</string>
<string-array name="pref__app_theme_values">
<item>#string/pref__app_theme__cards_ui</item>
<item>#string/pref__app_theme__cards_ui_dark</item>
</string-array>
</resources>
res/values/strings.xml
<resources>
<string name="app_name">My Application</string>
<string name="app_theme">App Theme</string>
<string name="cards_light">cards light</string>
<string name="cards_dark">cards dark</string>
</resources>
res/xml/pref_general.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<!-- theme -->
<ListPreference
android:defaultValue="#string/pref__app_theme_default"
android:entries="#array/pref__app_theme_entries"
android:entryValues="#array/pref__app_theme_values"
android:key="#string/pref__app_theme"
android:title="#string/app_theme"/>
<EditTextPreference android:key="#string/pref__custom_app_theme"/>
</PreferenceScreen>
SettingsActivity.java
public class SettingsActivity extends PreferenceActivity
{
public interface IOnListPreferenceChosenListener
{
public void onChosenPreference(String key,String entry,String value);
}
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
final EditTextPreference editTextPreference=(EditTextPreference)findPreference(getString(R.string.pref__custom_app_theme));
final ListPreference listPreference=prepareListPreference(this,R.string.pref__app_theme,R.array.pref__app_theme_entries,R.array.pref__app_theme_values,R.string.pref__app_theme_default,new IOnListPreferenceChosenListener()
{
#Override
public void onChosenPreference(final String key,final String entry,final String value)
{
editTextPreference.setTitle(value);
editTextPreference.setSummary(entry);
}
});
editTextPreference.setTitle(listPreference.getValue());
editTextPreference.setSummary(listPreference.getEntry());
}
public static ListPreference prepareListPreference(final PreferenceActivity activity,final int prefKeyId,//
final int entriesId,final int valuesId,final int defaultValueId,final IOnListPreferenceChosenListener listener)
{
final String prefKey=activity.getString(prefKeyId);
#SuppressWarnings("deprecation")
final ListPreference pref=(ListPreference)activity.findPreference(prefKey);
final String[] entries=activity.getResources().getStringArray(entriesId);
final String[] values=activity.getResources().getStringArray(valuesId);
final String defaultValue=activity.getResources().getString(defaultValueId);
final String currentValue=PreferenceManager.getDefaultSharedPreferences(activity).getString(prefKey,defaultValue);
for(int i=0;i<values.length;++i)
{
final String value=values[i];
if(TextUtils.equals(currentValue,value))
{
pref.setSummary(entries[i]);
pref.setValueIndex(i);
break;
}
}
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
#Override
public boolean onPreferenceChange(final Preference preference,final Object newValue)
{
final String newValueStr=newValue.toString();
String entryChosen=null;
for(int i=0;i<values.length;++i)
{
final String value=values[i];
if(TextUtils.equals(newValueStr,value))
{
entryChosen=entries[i];
break;
}
}
pref.setSummary(entryChosen);
if(listener!=null)
listener.onChosenPreference(prefKey,entryChosen,newValueStr);
return true;
}
});
return pref;
}
}

Related

Android can't figure out why perference screen won't show preference textbox

I'm trying to display preference screen and with a text box and doesn't show but in another screen it has no problem? It shows a negative 1 or null.
StatsActivity
public class StatsActivity extends Activity {
static final String TAG = "StatsActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stats_settings_layout);
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
StringBuilder builder = new StringBuilder();
builder.append("\n" + sharedPrefs.getString("time_usage_key", "-1"));
TextView settingsTextViewStats = (TextView) findViewById(R.id.stats_settings_text_view);
settingsTextViewStats.setText(builder.toString());
}
}
StatsPrefsActivity
public class StatsPrefsActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener{
static final String TAG = "StatsPrefsActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences_stats);
PreferenceManager.setDefaultValues(this,R.xml.preferences_stats, false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//menu.add(Menu.NONE, 0, 0, "Show current settings");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
startActivity(new Intent(this, StatsActivity.class));
return true;
}
return false;
}
#Override
public void onStart(){
super.onStart();
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(StatsPrefsActivity.this);
}
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
SharedPreferences s = getSharedPreferences("MY_PREFS", 0);
// Create a editor to edit the preferences:
SharedPreferences.Editor editor = s.edit();
}
}
preference_stats.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Settings"
android:key="first_category">
<EditTextPreference
android:id="#+id/text_pref_box"
android:key="time_usage_key"
android:title="7 Day Usage"
android:summary="A total of usage of 7 days." />
</PreferenceCategory>
</PreferenceScreen>
if you want an inital value then set one. right now you have "-1" set as the default value. so if the preference has never been used before your going to get "-1" as the default. Try changing that to a blank string "" or something if you want better presentation.

Android spinner refresh without using an OnItemSelectedListener

I have an issue I have been unable to figure out. I have a spinner loaded from an ArrayList saved in SharedPreferences. I allow the users to modify the spinner names through a PreferenceActivity in a separate class that is startActivityForResult. It works but I cannot for the life of me make the spinner refresh itself with the new name(s) unless the app is closed and then reopened.
When the user uses the back key to close the Edit names window the result code and result_ok information is passed back correctly. This is where I can't figure things out. I know I need to use NotifyDataSetChanged but I can't figure out how to do it since the modifications are made in a separate class and not in the OnItemSelectedListener like so many answers to questions here on StackOverflow suggest for refreshing spinner data.
Here is my spinner code:
private ArrayAdapter<String> adapter1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
/* enable hardware acceleration on Android >= 3.0 */
final int FLAG_HARDWARE_ACCELERATED = WindowManager.LayoutParams.class
.getDeclaredField("FLAG_HARDWARE_ACCELERATED").getInt(null);
getWindow().setFlags(FLAG_HARDWARE_ACCELERATED,
FLAG_HARDWARE_ACCELERATED);
} catch (Exception e) {
}
checkPreferences();
setContentView(R.layout.main);
this.findViewById(R.id.label_mode).setOnClickListener(this);
this.findViewById(R.id.label_clear).setOnClickListener(this);
this.findViewById(R.id.label_data).setOnClickListener(this);
this.findViewById(R.id.label_wifi).setOnClickListener(this);
this.findViewById(R.id.label_roam).setOnClickListener(this);
this.findViewById(R.id.label_vpn).setOnClickListener(this);
this.findViewById(R.id.label_invert).setOnClickListener(this);
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
// create the spinner
spinner = (Spinner) findViewById(R.id.spinner);
// profile names for spinner
final List<String> profilestring = new ArrayList<String>();
profilestring.add(prefs.getString("default",
getString(R.string.defaultprofile)));
profilestring.add(prefs.getString("profile1",
getString(R.string.profile1)));
profilestring.add(prefs.getString("profile2",
getString(R.string.profile2)));
profilestring.add(prefs.getString("profile3",
getString(R.string.profile3)));
profilestring.add(prefs.getString("profile4",
getString(R.string.profile4)));
profilestring.add(prefs.getString("profile5",
getString(R.string.profile5)));
profileposition = profilestring
.toArray(new String[profilestring.size()]);
// adapter for spinner
adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, profileposition);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter1);
spinner.setSelection(prefs.getInt("itemPosition", 0));
spinner.post(new Runnable() {
public void run() {
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
int index = parent.getSelectedItemPosition();
if (index == 0) {
editor.putInt("itemPosition", index);
editor.commit();
LoadDefaultProfile();
}
if (index == 1) {
editor.putInt("itemPosition", index);
editor.commit();
LoadProfile1();
}
if (index == 2) {
editor.putInt("itemPosition", index);
editor.commit();
LoadProfile2();
}
if (index == 3) {
editor.putInt("itemPosition", index);
editor.commit();
LoadProfile3();
}
if (index == 4) {
editor.putInt("itemPosition", index);
editor.commit();
LoadProfile4();
}
if (index == 5) {
editor.putInt("itemPosition", index);
editor.commit();
LoadProfile5();
}
}
public void onNothingSelected(AdapterView<?> parent) {
// do nothing
}
});
}
});
I then set my selection and run the spinner with spinner.post(New Runnable).
My preference screen is very simple.
<?xml version="1.0" encoding="utf-8"?>
<EditTextPreference
android:key="default"
android:summary="Edit name for Default Profile"
android:title="#string/defaultprofile" />
<EditTextPreference
android:key="profile1"
android:summary="Edit name for profile1"
android:title="#string/profile1" />
<EditTextPreference
android:key="profile2"
android:summary="Edit name for profile2"
android:title="#string/profile2" />
<EditTextPreference
android:key="profile3"
android:summary="Edit name for profile3"
android:title="#string/profile3" />
<EditTextPreference
android:key="profile4"
android:summary="Edit name for profile4"
android:title="#string/profile4" />
<EditTextPreference
android:key="profile5"
android:summary="Edit name for profile5"
android:title="#string/profile5" />
EditNames class
public class EditProfileNames extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.prefs);
PreferenceManager.setDefaultValues(EditProfileNames.this,
R.layout.prefs, false);
for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
initSummary(getPreferenceScreen().getPreference(i));
}
}
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
updatePrefSummary(findPreference(key));
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
p.setSummary(editTextPref.getText());
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
resultOk();
}
return super.onKeyDown(keyCode, event);
}
/**
* Set the activity result to RESULT_OK and terminate this activity.
*/
private void resultOk() {
final Intent response = new Intent(Api.PREF_PROFILES);
setResult(RESULT_OK, response);
finish();
}
}
So what do I have to do to refresh the spinner? I know I could do it if the change was made in the OnItemSelectedListener but since it is an entirely different class that makes the changes I'm lost at the moment.
Thanks!
It sounds like you are passing a reference to your array, profileposition, to another class so that it can add elements to it. You will also need to pass a reference to adapter to that class as well, so that it can call adapter.notifyDataSetChanged(); after it has updated your array.
EDIT: Now that I see that you an Acitivty that you have started for a result is doing the updating of the array, you could just call adapter.notifyDataSetChanged(); in your onActivityResult() callback.
After changing the contents , call notifyDataSetChanged on the adapter and that will solve the issue.
Try this way
adapter.notifyDataSetChanged();

Android: update ListPreference with OnPreferenceChangeListener

Here's my preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<ListPreference
android:key="KEY_1"
android:title="Title"
android:summary="Summary"
android:dialogTitle="Dialog"
/>
<ListPreference
android:key="KEY_2"
/>
<ListPreference
android:key="KEY_3"
/>
<ListPreference
android:key="KEY_4"
/>
And here is the Settings.java:
public class Settings extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
// some methods to generate entries and values for ListPreference
final List List_1 = // something
final List List_2 = // something
final List List_3 = // something
String[] entry_1 = List_1.toArray(new String[List_1.size()]);
String[] entry_2 = List_2.toArray(new String[List_2.size()]);
String[] entry_3 = List_3.toArray(new String[List_3.size()]);
String[] value_1 = List_1.toArray(new String[List_1.size()]);
String[] value_2 = List_2.toArray(new String[List_2.size()]);
String[] value_3 = List_3.toArray(new String[List_3.size()]);
// set arrays for entries and values
final ListPreference lp1 = (ListPreference)findPreference("KEY_1");
lp1.setEntries(entry_1);
lp1.setEntryValues(value_2);
ListPreference lp2 = (ListPreference)findPreference("KEY_2");
lp2.setEntries(entry_2);
lp2.setEntryValues(value_1);
ListPreference lp3 = (ListPreference)findPreference("KEY_3");
lp3.setEntries(entry_2);
lp3.setEntryValues(value_2);
ListPreference lp4 = (ListPreference)findPreference("KEY_4");
lp4.setEntries(entry_2);
lp4.setEntryValues(value_3);
// update lp2, lp3, lp4
lp1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String listValue = (String) newValue;
ListPreference lp2 = (ListPreference)findPreference("KEY_2");
lp2.setDefaultValue(listValue);
ListPreference lp3 = (ListPreference)findPreference("KEY_3");
lp3.setDefaultValue(listValue);
ListPreference lp4 = (ListPreference)findPreference("KEY_4");
lp4.setDefaultValue(listValue);
return true;
}
});
}
}
This works well for me for only one time. What am I missing here to make the updates on lp2, lp3 and lp4 later on? I guess setDefaultValue creates just that one-time-input to shared preferences?
I suspect your anonymous listener is garbage collected - add some debug prints to see if the listener is called
lp1.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Log.d("Listener", "I listen");
String listValue = (String) newValue;
// rest is the same
}
});
If you see no debug print move your listener to a class field and :
public class Settings extends PreferenceActivity {
private OnPreferenceChangeListener mListener=new OnPreferenceChangeListener(){
#Override
public boolean onPreferenceChange(Preference preference, Object newValue){
// as before
}
};
// etc - I guess the line below is in onCreate() - correct your formatting !
lp1.setOnPreferenceChangeListener(mListener);
}
}

Update Preference List

i'm trying to update my list in a preference with onPreferenceClick method. But the list isn't updated. onPreferenceClick is executed, because i got the names and showed it in the log, but not updated.
public class TransferPreference extends PreferenceFragment {
private TransferHelper transferHelper = new TransferHelper();
private ArrayList<String> names = new ArrayList<String>();
private CharSequence[] charSequence;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference_transfer);
final MultiSelectListPreference preferenceTeams = (MultiSelectListPreference) findPreference("preferenceTranser_multiSelectListPreference_teams");
preferenceTeams.setPersistent(false);
preferenceTeams.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
names = transferHelper.getServerTeams(getActivity());
int size = names.size();
charSequence = names.toArray(new CharSequence[size]);
preferenceTeams.setEntries(charSequence);
preferenceTeams.setEntryValues(charSequence);
return false;
}
});
}
}
I also tried this in onPreferenceClick:
Editor editor = preference.getEditor();
editor.clear();
names = transferHelper.getServerTeams(getActivity());
for (String name : names) {
editor.putString(name, name);
}
editor.commit();
If i put the following code direct in the oncreate method (and not in the listener method), the names are displayed. But only on its creation, like the name says :)
names = transferHelper.getServerTeams(getActivity());
int size = names.size();
charSequence = names.toArray(new CharSequence[size]);
preferenceTeams.setEntries(charSequence);
preferenceTeams.setEntryValues(charSequence);
Has anyone an idea?
Sorry for my bad english and thanks for help.
edit: i alos tried to add my code additional in this method, but no update.
#Override
public void onResume()

Is it possible to combine an EditTextPreference with a CheckBoxPreference?

I have a PreferenceActivity with, among other things, a category including call forward options. What I want is a preference that:
Enables/Disables if the user presses a checkbox on the right.
Opens up the EditTextPreference dialog if the user presses the text(or anything else in the preference)
It's probably not of any use but here is a snippet of this particular preferencecategory :
<PreferenceCategory
android:title="#string/category_callforward">
<EditTextPreference
android:key="call_forward_always"
android:title="#string/call_forward_always"
android:summary="#string/call_forward_forwardto" />
</PreferenceCategory>
EDIT
I'd like to implement it in this method if possible:
// Locates the correct data from saved preferences and sets input type to numerics only
private void setCallForwardType()
{
ep1 = (EditTextPreference) findPreference("call_forward_always");
EditText et = (EditText) ep1.getEditText();
et.setKeyListener(DigitsKeyListener.getInstance());
}
EDIT2
If anyone is still wondering - this is what I want as a Preference:
EDIT3
I've searched around for a couple hours now and have come up with a single word: 'PreferenceGroupAdapter'. I have not, however, been able to find examples or tutorials showing me how to use it. Suggestions ? Is this even the correct path to go?
EDIT4
If this really isn't possibly I would very much like a suggestion to an alternative(user-friendly) solution that I can implement instead of the combined Edit- and Checkbox preference.
You can do this. First, create a class for preferences which should be extended from PreferenceActivity. Use like this:
// editbox ise your EditTextPreference, so set it.
checkbox = (CheckBoxPreference) findPreference("checkbox_preference");
checkbox.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChange(Preference preference, Object newValue) {
if(newValue.toString().equals("false")) {
PrefActivity.this.editbox.setEnabled(false);
} else if(newValue.toString().equals("true")) {
PrefActivity.this.editbox.setEnabled(true);
}
return true;
}
});
I hope it helps.
A bit late but I think I've managed to create something similar with a dialog that creates a layout with an edit text and a checkbox, it should be possible to do the same in a normal layout:
public class CheckEditTextPreference extends DialogPreference {
private static final String KEY_PROPERTY_DISABLED = "key_property_disabled";
private EditText editText;
private CheckBox checkBox;
private String text;
private boolean isDisabled;
private SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
public CheckEditTextPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
protected View onCreateDialogView() {
return buildUi();
}
/**
* Build a dialog using an EditText and a CheckBox
*/
private View buildUi() {
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(25, 0, 0, 0);
LinearLayout linearLayout = new LinearLayout(getContext());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(layoutParams);
checkBox = new CheckBox(getContext());
editText = new EditText(getContext());
editText.setLayoutParams(layoutParams);
checkBox.setLayoutParams(layoutParams);
checkBox.setText("Disabled");
FrameLayout dialogView = new FrameLayout(getContext());
linearLayout.addView(editText);
linearLayout.addView(checkBox);
dialogView.addView(linearLayout);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editText.setEnabled(!isChecked);
}
});
return dialogView;
}
#Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
checkBox.setChecked(isDisabled());
editText.setText(getText());
}
#Override
protected void onDialogClosed(boolean positiveResult) {
if (positiveResult) {
String text = editText.getText().toString();
boolean isChecked = checkBox.isChecked();
if (callChangeListener(text)) {
setText(text);
}
if (callChangeListener(isChecked)) {
isDisabled(isChecked);
}
}
}
#Override
protected Object onGetDefaultValue(TypedArray a, int index) {
return a.getString(index);
}
#Override
protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
setText(restorePersistedValue ? getPersistedString("") : defaultValue.toString());
isDisabled(mySharedPreferences.getBoolean(KEY_PROPERTY_DISABLED, true));
}
public void setText(String value) {
this.text = value;
persistString(this.text);
}
public String getText() {
return this.text;
}
private void isDisabled(boolean value) {
this.isDisabled = value;
mySharedPreferences.edit().putBoolean(KEY_PROPERTY_DISABLED, this.isDisabled).apply();
}
public boolean isDisabled() {
return this.isDisabled;
}
}
And put this into your preferences screen:
<your.package.name.CheckEditTextPreference
android:key="chkEtPref"
android:title="Title"/>
Define a key in res/values/strings.xml for your CheckBoxPreference.
Give your CheckBoxPreference the XML attribute android:key="#string/THE_KEY_YOU_DEFINED" so that it will automatically save state in SharedPreferences.
Give your EditTextPreference the XML attribute android:dependency="#string/THE_KEY_YOU_DEFINED.
The EditTextPreference should then enable / disable depending on the state of the CheckBoxPreference.

Categories

Resources