How to set maximal length of EditTextPreference of AndroidX Library? - android

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()

Related

How can be able to use conter min length in TextInputLayout

I have an EditText wrapped in a TextInputLayout. The TextInputLayout has an option for maximum length. Example below:
app:counterMaxLength="12"
Is it possible to have an option for counterMinLength? For example, if I am entering a password where the length cannot be less than a certain length.
I don't think it has an attribute like that, because when activity created it has an empty string value which breaks "min length" constraint.
So to resolve that I think you should verify the length in java/kotlin code like:
if(editText.getText().toString().length() > MIN_VALUE) {
// do somthing
}
I dont think that they are supporting this option at the moment :)
But I think if you want you can easily create a custom Edittext and then validate the minimum number of input field by using
edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
if (edt.getText().toString().trim().length() < 8) {
edt.setError("Minimum length exception");
}
}
or you can you addTextChangedListener for your edittext
Something like that. ^^

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."));
});

setHint doesnt work with setInputType

I build EditText dynamically. Among other things, I set 2 properties: hint(.setHint) and inputType(.setInputType). My problem: when I invoke setInputType, setHint has no effect: blank edittexts remain blank with no hint. Once I comment out setInputType, I see all hints. I need both input type and hint. What to do? My code:
private EditText buildTextBox(Property property)
{
EditText control = new EditText(this);
control.setInputType(getInputTypeByPropertyInputType(property.getType()));// android.text.InputType.
control.setHint(property.getDisplayName());
return control;
}
private int getInputTypeByPropertyInputType(String type)
{
if (type.equals("integer"))
{
return android.text.InputType.TYPE_CLASS_NUMBER;
}
else
{
return android.text.InputType.TYPE_CLASS_TEXT;
}
}
#Eugene
Ensure you call control.SetHint() just before you call the control.setGravity() and control.setInputType(); and it works for me verrry much!
column1 = new EditText(this);
column1.setId(i);
column1.setHint("Value");
column1.setInputType(InputType.TYPE_CLASS_NUMBER);
column1.setGravity(Gravity.RIGHT);
I agree with Eugene.
Remove the gravity(just don't use CENTER) and the hint texts will come back as normal.
Nice find!

Android EdittextPreference Hint (android:hint)

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.
}
}

How to set editable true/false EditText in Android programmatically?

We can set editable property of EditText in XML layout but not programatically, but there is no setEditable() method!
If EditText is not Enabled [ by setEnabled(false)] it still Editable!
This may help:
if (cbProhibitEditPW.isChecked()) { // disable editing password
editTextPassword.setFocusable(false);
editTextPassword.setFocusableInTouchMode(false); // user touches widget on phone with touch screen
editTextPassword.setClickable(false); // user navigates with wheel and selects widget
isProhibitEditPassword= true;
} else { // enable editing of password
editTextPassword.setFocusable(true);
editTextPassword.setFocusableInTouchMode(true);
editTextPassword.setClickable(true);
isProhibitEditPassword= false;
}
I did it in a easier way , setEditable and setFocusable false. but you should check this.
How to replicate android:editable="false" in code?
Fetch the KeyListener value of EditText by editText.getKeyListener()
and store in the KeyListener type variable, which will contain
the Editable property value:
KeyListener variable;
variable = editText.getKeyListener();
Set the Editable property of EditText to false as:
edittext.setKeyListener(null);
Now set Editable property of EditText to true as:
editText.setKeyListener(variable);
Note: In XML the default Editable property of EditText should be true.
How to do it programatically :
To enable EditText use:
et.setEnabled(true);
To disable EditText use:
et.setEnabled(false);
hope this one helps you out:
edittext1.setKeyListener(null);
edittext1.setCursorVisible(false);
edittext1.setPressed(false);
edittext1.setFocusable(false);
editText.setInputType(InputType.TYPE_NULL);
Once focus of edit text is removed, it would not allow you to type even if you set it to focusable again.
Here is a way around it
if (someCondition)
editTextField.setFocusable(false);
else
editTextField.setFocusableInTouchMode(true);
Setting it true in setFocusableInTouchMode() seems to do the trick.
try this,
EditText editText=(EditText)findViewById(R.id.editText1);
editText.setKeyListener(null);
It works fine...
Try this it is working fine for me..
EditText.setInputType(0);
EditText.setFilters(new InputFilter[] {new InputFilter()
{
#Override
public CharSequence filter(CharSequence source, int start,
int end, Spanned dest, int dstart, int dend)
{
return source.length() < 1 ? dest.subSequence(dstart, dend) : "";
}
}
});
editText.setFocusable(false);
editText.setClickable(false);
Since setEditable(false) is deprecated, use textView.setKeyListener(null); to make editText non-clickable.
Since the setEditable(false) is deprecated and we can't use it programmatically, we can use another way to solve it with setInputType(InputType.TYPE_NULL)
It means we change the input type of edit text. We set it to NULL so it becomes not editable.
Here's the sample that might be useful (I code this on my onCreateView method Fragment):
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.yourfragment, container, false);
EditText sample = view.findViewById(R.id.youredittext);
sample.setInputType(InputType.TYPE_NULL);
Hope this will answer the problem
An easy and safe method:
editText.clearFocus();
editText.setFocusable(false);

Categories

Resources