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

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.

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

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

How would i store a number/string into R.string.xx?

with this code, my program just force close(error)
***public View x = findViewById(R.string.nfoname);***
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
//edittext
***final EditText infoname=(EditText)findViewById(R.id.infoname);***
//clear,confirm
Button clear = (Button)findViewById(R.id.buttonclear);
Button confirm = (Button)findViewById(R.id.buttonconfirm);
//clear button
clear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
infoname.setText("");
}
});
//confirm button
confirm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
***x=(View) infoname.getText();***
}
});
}
the one with the * are the source of error
program function:
if the user clicks confirm, his name will be set to R.string.nfoname
which will then be used in another layout through TextView x = setText(R.string.nfoname);
I am not sure that you can save text to the R.string. This is a generated class that the compiler creates for you. It gets packaged with your apk. Think of the resources as a means of translation and to present text to the screen.
I think what you would want to do is save the user input as a SharedPreference or in a database.
See:SharedPreferences on the android docs for an example usage.
At least in the case of your variable infoname scoping is most likely causing your application to throw an error. infoname is a local variable to the function onCreate(), not an instance variable for your class, so it can't be accessed by your onClick() methods because they are part of an anonymous class.
Another thing I'd question is why you marked infoname as final? It goes out of scope when onCreate() exits so if it gets changed, you can see who changed it since it only exists while the method is executing.
You cannot set values to R.string.xxx because all these values will be constants much like a read only stuff. If you want to use the value of edit text to another layout use class variables or intent.putextra()
Coming to ur source code i see this
public View x = findViewById(R.string.nfoname);
How can a view be found by R.String? This should be R.id.
final EditText infoname=(EditText)findViewById(R.id.infoname);
Why this editText has to be final?
***x=(View) infoname.getText();***
You just use infoname.getText().toString() you will get the string value of the Edittext's current text.
Dude you can do stuff simply.
public View x = findViewById(R.string.nfoname);
This can't work as not only are you trying to find a View using a R.string resource id, you are doing it before setContenView(...) is called in your onCreate(...) method. Even if you used a valid View resource id such as R.id.infoname then x will be null because the content view hasn't been inflated yet.
final EditText infoname=(EditText)findViewById(R.id.infoname);
Apart from the pointless use of final this should'nt cause problems as long as R.id.infoname is actually the resource id of an EditText.
x=(View) infoname.getText();
Not only will x be null but calling getText() on an EditText returns an Editable which is not a View nor is it possible to cast it to View. Even if you used getText().toString() which is the correct way to get the text from an EditText it still wouldn't be possible to cast a String to a View.
Also, as for this...
TextView x = setText(R.string.nfoname);
It would have to be...
TextView x = (TextView) findViewById(<some id>);
x.setText(getString(R.string.nfoname));

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

Categories

Resources