Android EdittextPreference Hint (android:hint) - android

I have a preference screen with an EditTextPreference.
How to set a hint
either in xml like
android:hint
or in code like
setHint(int), setHint(CharSequence hint)
on the EditTextPreference like on an EditText field?
I assumed that it´s like on the EditText but i didn´t find anything like this.
Thanks.

It's exactly the same to set a hint in XML for an EditTextPreference as it is for an EditText:
android:hint="This is my hint"
This gets passed through to the EditText in the dialog.
This behaviour is confirmed here where it says "It is a subclass of DialogPreference and shows the EditText in a dialog. This EditText can be modified either programmatically via getEditText(), or through XML by setting any EditText attributes on the EditTextPreference."

this is way better, as the accepted answer will not set a hint on the edittext but will set the text to
the EditText (long live the small differene).
To really set a hint, use this code:
YourEditTextPreference.getEditText().setHint(R.string.some_hint);
you may also consider adding a summary so the preference will not be displayed with an empty summary

If you are using the AndroidX preference library, you can assign a hint using an OnBindEditTextListener in your PreferenceFragmentCompat:
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
PreferenceManager manager = getPreferenceManager();
EditTextPreference textPref = manager.findPreference("myTextPreference");
textPref.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
#Override
public void onBindEditText(#NonNull EditText editText) {
editText.setHint(R.string.hint);
}
});
}
When the input field is empty, the hint should then be displayed as expected.

Kotlin version (AndroidX preference library):
val editTextPref = findPreference<Preference>("prefKey") as EditTextPreference
editTextPref.setOnBindEditTextListener {
it.hint = "My hint"
}
Works in emulator with Android 10 (API level 29).
At the same time, the hint specified in xml does not work:
<EditTextPreference
android:key="prefKey"
android:title="Title"
android:hint="My hint"/>

Use android:summary to give a brief description of your preference.
You can also set this dynamically using setSummary(CharSequence summary) .
EDIT: for giving a 'hint' you could use android:defaultValue .

the way to set "Hints" is to use a summary provider as described in
https://developer.android.com/guide/topics/ui/settings/customize-your-settings
the idea is to print a default/hint when the value is null or empty - otherwise, just print out the preference value
val dobPreference: EditTextPreference? = findPreference("key_dob")
dobPreference?.summaryProvider = SummaryProvider<EditTextPreference> { pref ->
if (pref.text.isNullOrBlank()) {
"e.g. Enter your DOB in DDMMYYYY format" // the hint if pref is empty
} else {
pref.text // your preference value if it is not empty.
}
}

Related

How to set maximal length of EditTextPreference of AndroidX Library?

Recently, I migrate my android project to AndroidX and I use the EditTextPreference from AndroidX library. Now, I want to set the maximum length of the EditTextPreference to let say 50. I have tried to use:
android:maxLength="50"
but it's not working.
It seems that all android namespace won't work with the EditTextPreference and there is no code suggestion so I cannot find any related code to set the maximum length. How can I set the maximum length?
You need find your EditTextPreference by key, then set onBindEditTextListener to it and change layout attributes at the onBindEditText method:
EditTextPreference preference = findPreference("edit_text_preference_key");
preference.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
#Override
public void onBindEditText(#NonNull EditText editText) {
editText.setInputType(InputType.TYPE_CLASS_NUMBER); // set only numbers allowed to input
editText.selectAll(); // select all text
int maxLength = 2;
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)}); // set maxLength to 2
}
});
You can put this code to onResume() method of yout PreferencesFragment or PreferencesActivity.
You may try with java code, that will works.
Here is snipped.
EditText et = (EditText) findViewById(R.id.myeditText);
et.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(50) }); // maximum length is 50
I hope that will help you.
This is the code to set maximal length (in this case 10) of EditTextPreference:
final EditTextPreference prefCustomText = findPreference(ActivityPreferences.PREF_DISPLAY_CUSTOM_TEXT);
prefCustomText.setOnBindEditTextListener(editText -> {
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
});
And I'm adding information as wrote #Viktor Brešan:
I think you should append the new InputFilter to ones that might have
been added to EditText previously. You can get them by calling
editText.getFilters()

Hiding edit text in onCreate, but then not storing values once values entered for EditText, clipEx has text data false

The app crashes when the button is selected which uses the values converted from edit texts. Tried multiple ways to move the part edittext = R.ids .. to try and make sure the edittexts picks new values after the oncreate first runs.
Think the calculation part causes the crash because its trying to perform a calculation with stored values from the edit text when the value is false from the first time the edit text gets the R.ids... in the onCreate method.
needed hide/display editText based off a radio button setonCheckedChangeListener in the onCreate method. So edittext = R.ids .. set in this method, the app does not crash at runtime like it would if I moved the edittext = R.ids .. to the testFunction method.
EditText editTextValue;
EditText editTextValue2;
double amount;
protected void onCreate(){...
//Get edittext field parameters
editTextValue = (EditText) findViewById(R.id.editText_weight_kg);
//listener to switch editTexts on which radio button selected in units group
unitsRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.imperial) {
editTextValue2.setVisibility(View.VISIBLE);
editTextValue.setVisibility(View.GONE);
}
void testFunction(View view){
String stringValue = editTextValue..getText().toString();
//check value as long as its not empty for the edit text , save it
if (editTextValue.getText().length() > 0) {
amount = Integer.parseInt(stringValue);
Log.e("MainActivity", " " + amount);
}
}
but now when I run the app I get this error in the long cat
enter image description here
E/ClipboardServiceEx﹕ clipEx is android.sec.clipboard.ClipboardExManager#1f70b420
E/ClipboardServiceEx﹕ clipEx has text data : false
here is the xml for one of the edit texts
<EditText
android:id="#+id/editText_weight_lb"
style="#style/EditTextViewStyle"
android:visibility="visible"/>
In the editTextStyle , I set the textCursorDrawable to null to try and have different colors for the pointer and underline colors. Not sure if this could also be affecting the editTextView storing the value
<item name="android:textCursorDrawable">#null</item>
I also tried setting edittext = R.ids in the testfunction and in the onCreate method. See if the editTexts would store the values the user enters rather than keeping the empty values when onCreate initially run.
I still got the same clipEx has text data:false error after trying this.
I searched the logcat error "clipEx has text data: false" and found something regarding samsung memory leaks.
https://github.com/square/leakcanary/issues/133
I am using a samsung galaxy for testing. I feel the issue is more with where I'm setting the edittexts to the R.ids thats causing the issue.
I saw the post for checking to make sure valid value entered for edittext.
Issue with empty EditText
How to Check whether a value is entered in editexts before submitting?
will add the check after finding out why values are not getting stored/ still remaining false.
Thanks
well I tried a different approach to implement the method.
I placed a button in the OnCreate method to define the event handlers against the buttons:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button calculate = (Button)findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener(){
String stringValue = editTextValue.getText().toString();
//check value as long as its not empty for the edit text , save it
if (editTextValue.getText().length() > 0) {
amount = Integer.parseInt(stringValue);
Log.e("MainActivity", " " + amount);
}
.....
.....
}
}
By using the button method in the OnCreate, when I ran the app, errors would actually come up on the Integer.parseInt() method call. Turns out that even though the editTexts that I was entering text for did not have text values, the other editTexts still had strings for the text, so this would cause the app to crash.
<EditText...
android:text="kg"/>
I took out the text values. It worked again.
I also took out this line in the style sheet for the editText. This was to change the editText border color, cursor color, or line.
<item name="android:textCursorDrawable">#null</item>
I tried the public void testFunction() approach which I had used before, the app works, but the clipEx has text data : false continues to show up.
But the app works now with either the Button method in onCreate or as a public void testFunction() approach.

How can we use android:inputType in EditTextPreference?

I checked the documentation of EditTextPreference
http://developer.android.com/reference/android/preference/EditTextPreference.html
But I failed to found the android:inputType attribute there. Then how it can be used in this code segment
<EditTextPreference
android:key="edit"
android:title="#string/location1"
android:summary="#string/summary1"
android:dialogTitle="#string/location1"
android:dialogMessage="#string/message"
android:inputType="text"
android:singleLine="true"
/>
Same doubt for the android:singleLine attribute.
The docs don't list the attributes for that class, but the InputType attribute (and other EditText and TextView attributes) still work. It's only stated in the text. Also see this related question.
The EditTextPreference documentation doesn't explicitly list all the attributes it supports, but the text states:
See EditText Attributes.
The link there isn't very useful (they probably reorganised some of the attributes but never updated some links to it), but here's a direct link to inputType values. As a quick summary those values are (as of the time of posting):
none
text
textCapCharacters
textCapWords
textCapSentences
textAutoCorrect
textAutoComplete
textMultiLine
textImeMultiLine
textNoSuggestions
textUri
textEmailAddress
textEmailSubject
textShortMessage
textLongMessage
textPersonName
textPostalAddress
textPassword
textVisiblePassword
textWebEditText
textFilter
textPhonetic
textWebEmailAddress
textWebPassword
number
numberSigned
numberDecimal
numberPassword
phone
datetime
date
time
You can apparently use one or more of these, separated by a | (I've never done this though).
You can't do it from XML, but EditTextpreference exposes the EditText so you can do it programmatically. After you load the preferences in your Activity/Fragment, you can do:
EditTextPreference pref = (EditTextPreference) PreferenceManager.findPreference("edit");
EditText prefEditText = pref.getEditText();
prefEditText.setInputType(InputType.TYPE_CLASS_TEXT);
prefEditText.setSingleLine(true);
// etc
Using AndroidX, to set input type to password for example:
root_preferences.xml:
<androidx.preference.PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<Preference
android:title="Password"
android:key="my_pref_password"/>
</androidx.preference.PreferenceScreen>
And in your Setting Fragment:
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
EditTextPreference pref = findPreference("my_pref_password");
pref.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
#Override
public void onBindEditText(#NonNull EditText editText) {
editText.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
});
}
You can find an answer to your question here
Basically, you will need to import androidX library and follow my code.
#Simplest and Tested Answer#
For Only Decimal Value in EditTextPreference
Write this code in onCreatePreferences
Make sure use both CLASS and Attributes of that class
Example
InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
public static class SettingsFragment extends PreferenceFragmentCompat {
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.root_preferences, rootKey);
EditTextPreference new_bonus= findPreference("new_bonus");
EditTextPreference old_bonus= findPreference("old_bonus");
EditTextPreference.OnBindEditTextListener onBindEditTextListener = new EditTextPreference.OnBindEditTextListener() {
#Override
public void onBindEditText(#NonNull EditText editText) {
editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
}
};
old_bonus.setOnBindEditTextListener(onBindEditTextListener);
new_bonus.setOnBindEditTextListener(onBindEditTextListener);
}
}

how to set only numeric value for EditTextPreference in android?

how to set only numeric value for EditTextPreference in android.
I want a user to enter a port number not sure how can I put the limitation there
I am using this code, user can enter any string. Want to limit the user to atleast numbers only
<EditTextPreference
android:defaultValue="4444"
android:key="port"
android:title="Port"
android:dependency="service_on"
/>
EditTextPreference widgets should take the same attributes as a regular EditText, so use:
android:inputType="number"
Or more specifically use:
android:inputType="numberDecimal"
android:digits="0123456789"
since you want to limit the input to a port number only.
I use an androidX library because this library has a possibility to customize an input type of EditTextPreference dialog. AndroidX is a major improvement to the original Android Support Library so is suggested that everybody use this library.
You can read more about AndroidX here.
Here is my code where I use EditTextPreference inside of onCreatePreference method:
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preference, rootKey);
androidx.preference.EditTextPreference editTextPreference = getPreferenceManager().findPreference("use_key_from_editTextPreference_in_xml_file");
editTextPreference.setOnBindEditTextListener(new androidx.preference.EditTextPreference.OnBindEditTextListener() {
#Override
public void onBindEditText(#NonNull EditText editText) {
editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
}
});
}
After you use this code and click on editTextPreference, the dialog will pop up and your keyboard input type will be only numeric.
Using androidx.preference library, since androidx.preference:preference:1.1.0-alpha02 which is realeased on 2018.12.17, the library adds EditTextPreference.OnBindEditTextListener interface, which allows you to customize the EditText displayed in the corresponding dialog after the dialog has been bound.
So in this case, all you have to do is to add the Kotlin code below.
val editTextPreference = preferenceManager.findPreference<EditTextPreference>("YOUR_PREFERENCE_KEY")
editTextPreference.setOnBindEditTextListener { editText ->
editText.inputType = InputType.TYPE_CLASS_NUMBER
}
EditTextPreference with decimal number input (Kotlin):
var myEditTextPreference : EditTextPreference? = findPreference("myEditTextPreferenceKey")
myEditTextPreference?.setOnBindEditTextListener { editText ->
editText.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL
}
Kotlin Code which worked for me:
Here "editTextPrefSleepTime" is a key of EditTextPreference, which I set on xml file.
private var editTextPrefSleepTime: EditTextPreference? = null
override fun onStart() {
super.onStart()
editTextPrefSleepTime = preferenceManager.findPreference("editTextPrefSleepTime")
editTextPrefSleepTime?.setOnBindEditTextListener {
it.inputType = InputType.TYPE_CLASS_NUMBER
}
}
Access the EditTextPreference's EditText methods with getEditText and set the input type
EditTextPreference pref = (EditTextPreference) findPreference("pref_edit_text");
if (pref != null) {
pref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
}
Unfortunate the offical library android.support.v7.preference hide access to getEditText, but there is a fix library that soloves this.
For me, I wanted to allow digits and dots only so that users can type an IP address.
This is JAVA
androidx.preference.EditTextPreference toesIpText = getPreferenceManager()
.findPreference("toes_ip_address");
assert toesIpText != null;
toesIpText.setOnBindEditTextListener(editText -> {
editText.setInputType(InputType.TYPE_CLASS_TEXT);
editText.setKeyListener(DigitsKeyListener.getInstance("123456789."));
});

is there a way to specify the maximum length of a preference?

I would like limit a preference string to 20 characters... is there any way to do this? I mean limit the user to only being allowed 20 characters input.
For an EditText you can set the maximum length in the layout file using android:maxLength="20"
#MisterSquonk is right about how to handle it in the ui. You should also store it as a character string when saving your preferences.
If the preference you are asking is the EditTextPreference, you can set its attributes like this.
class MyEditTextPreference extends EditTextPreference {
#Override
protected void onBindView(View view) {
super.onBindView(view);
TextView summary = (TextView)view.findViewById(android.R.id.summary);
if (summary != null) {
summary.setSingleLine();
summary.setEllipsize(TextUtils.TruncateAt.MARQUEE);
}
}
But I guess other Preference provides the same onBindView as well for you to override.

Categories

Resources