How to force EditText to accept only numbers? - android

how to force the EditText to accept only numbers.?

Use android:inputType="number" in your layout XML

This also works fine:
android:digits="0123456789"

Or you can add the following:
yourEditText.setInputType(InputType.TYPE_CLASS_NUMBER |
InputType.TYPE_NUMBER_FLAG_DECIMAL |
InputType.TYPE_NUMBER_FLAG_SIGNED);
this will accept numbers, float point numbers and
negative numbers you can remove any of these as needed

You can use android:inputType="number" in the XML file. You can specify other values such as numberDecimal as well.
Also, you might additionally want to use android:singleLine="true" for a single line Edittext.
Also, look into android:numeric and android:maxLength. maxLength in particular can be useful for setting length limitations.

If you need support for decimal numbers use this:
android:inputType="numberDecimal"

This is the final solution:
public static void enforceEditTextUseNumberOnly(EditText field) {
Typeface existingTypeface = field.getTypeface();
field.setInputType((InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD));
field.setTransformationMethod(new NumericKeyBoardTransformationMethod());
field.setTypeface(existingTypeface);
if (field.getParent().getParent() instanceof TextInputLayout) {
((TextInputLayout) field.getParent().getParent()).setPasswordVisibilityToggleEnabled(false);
}
}
private static class NumericKeyBoardTransformationMethod extends PasswordTransformationMethod {
#Override
public CharSequence getTransformation(CharSequence source, View view) {
return source;
}
}

Related

Set default(unfocused) TextInputLayout hint textSize

I am trying to change hint text size programmatically, but I just can't find the right method. I'm using setHintTextAppearance, like it's shown in example, but it works only when input is focused or filled with some data. I tried to set EditText textSize also, but still no luck.
textInputLayout.setHintTextAppearance(Vabaco_TextInputLayout_hint_small);
EditText a = textInputLayout.getEditText();
a.setTextSize(8);
You can change hint text size when it unfocused using reflection like this;
try {
Field filed = TextInputLayout.class.getDeclaredField("mCollapsingTextHelper");
filed.setAccessible(true);
Object helper = filed.get(textInputLayout);
Field f1 = helper.getClass().getDeclaredField("mExpandedTextSize");
f1.setAccessible(true);
f1.set(helper,100);
}
catch (NoSuchFieldException | IllegalAccessException e) {
e.printStackTrace();
}
name of mExpandedTextSize may be different according to the dependency version for TextInputLayout. You should check TextInputLayout and CollapsingTextHelper classes for the name of variables.
Hope this helps you.
Reflection solution doesn't work on support:design:28.0.0(mExpandedTextSize-> expandedTextSize). Also, Android Q (and later) doesn't support some non-sdk solutions.
Create your custom layout:
public class CustomTextInputLayout extends TextInputLayout {
public CustomTextInputLayout(Context context) {
super(context);
}
#Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if(child instanceof EditText) {
((EditText)child).setTextSize(16);
}
super.addView(child, index, params);
}
}
If setting the text size programmatically is not required you can try like below,I have disabled TextInputLayout hint,
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:hintEnabled="false">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edittext"
android:hint="yorhint"
android:inputType="text"
android:textColorHint="#color/colorLightBlack"
android:textSize="10sp" />
</android.support.design.widget.TextInputLayout>
If required programmatically you can find edittext by id and set the text size.

EditText ellipsize (three dots...)

Unfortunatelly I am not able to make ellipsize for EditText works. Is even possible to put three dots at the end of the text when the text is too long? It is working perfectly for TextiView but not for EditText. Some idea?
android:id="#+id/ed_email_personalInfo"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="#color/transparent"
android:ellipsize="end"
android:ems="10"
android:hint="#string/email"
android:inputType="textEmailAddress"
android:maxLength="64"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:singleLine="true"
android:textColorHint="#color/col9a9a9a"
android:textSize="15.7sp"
Set this property to edit text.
Elipsize is working with disable edit text
android:lines="1"
android:scrollHorizontally="true"
android:ellipsize="end"
android:singleLine="true"
android:editable="false"
You have to remove android:inputType attribute.
Ellipsize doesn't work if inputType is defined.
Might not be possible in EditText (unless you create your own View). I think the default behavior (for singleLine EditText) is that you can scroll the text sideways when it can't fit in the view.
I'm not sure it answers the question (and I guess the original asker is not so interested anymore, after 7 and a half years), but I'm pretty confident my answer will come in handy to anyone stumbling into ellipsis issues with EditText.
Don't try to find any logic in this, but based on the answers from Oleksandr and Mubarak, I figured out the following:
To ellipsize an EditText in XML, use deprecated android:editable="false". In my case:
android:editable="false"
android:focusable="false"
android:singleLine="true"
android:maxLines="1"
android:ellipsize="end"
No need to mess with android:inputType="none" for the moment. The EditText looks just like a TextView and is properly ellipsized.
It is possible to make the EditText editable (and remove the ellipsis) like this:
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.setActivated(true);
editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS); // or whatever fits your needs
editText.setSingleLine(true);
editText.setEllipsize(null);
editText.requestFocus();
Your can then restore the EditText to its original state (ie. disguised as a TextView and properly ellipsized) like this:
editText.setFocusable(false);
editText.setFocusableInTouchMode(false);
editText.setActivated(false);
editText.setSingleLine(true);
editText.setKeyListener(null); // this is the key
editText.setEllipsize(TextUtils.TruncateAt.END);
You need write a new class that extends EditText. for example:
MyEditTextEllipsize extends EditText{
private String dotsString;
private String storeString;
public MyEditTextEllipsize(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
if(focused)
{
setText(storeString);
}else {
String NOW = getText().toString();
storeString = NOW;
if (NOW != null && getWidth() <= getTextSize() * NOW.length()) {
dotsString = NOW.substring(0, (int) (getWidth() / getTextSize())) + "...";
setText(dotsString);
}
}
}
}

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!

Only show number buttons on Soft Keyboard in Android?

On the soft keyboard in Android you can set the soft keyboard to show the numbers instead of a-z keyboard using android:inputType="numberDecimal". However, what do I do if I only want to show the top number row 1 2 3 4 5 6 7 8 9 0 and not the following rows starting with # # $ % ...?
Thanx for listening!
android:inputType="phone"
android:digits="1234567890"
is an option
You must only add this line on your code:
input.setRawInputType(Configuration.KEYBOARD_12KEY);
this will show only the numeric keyboard.
The phone number pad is the closest thing I've found (set inputType="phone" on your EditText).
The accepted answer did not work for me (tested on OnePlus 3t and Samsung Galaxy S6/S7 phones).
This solution uses numberPassword but overrides the default transformation method for the EditText to show characters instead of showing dots.
<EditText
android:id="#+id/userid"
android:inputType="numberPassword"
android:maxLength="6"
/>
// Numeric 6 character user id
EditText input = findViewById(R.id.userid);
// Process input and show characters instead of dots
input.setTransformationMethod(SingleLineTransformationMethod.getInstance());
Just posted an answer here but re-posting for simplicity:
Seems Android has added the functionality we were seeking. This is the xml I use for simple EditText numeric entry:
android:inputType="numberPassword"
android:digits="0123456789"
android:singleLine="true"
android:ems="4"
android:textColor="#android:color/black"
android:gravity="center"
The accepted answer didn't work for me. It kept showing other unwanted characters
I found a way to accomplish the behavior I wanted by changing the inputType to numberPassword and then disabling the password dots
textInput.inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_VARIATION_PASSWORD
textInput.transformationMethod = SingleLineTransformationMethod()
Last I looked into it, Android did not have any good options for that. I ended up having to write my own version of a soft keyboard-like user interface.
I had implemented this for android in Xamarin. So, my code is in C#. But the principal stays the same. You can set attribute of edittext to android:inputType="numberPassword".
Then within your code you attach custom transformation method to your edittext view.
holder.edtxtQty.TransformationMethod = new HiddenPasswordTransformationMethod();
private class HiddenPasswordTransformationMethod : global::Android.Text.Method.PasswordTransformationMethod
{
public override Java.Lang.ICharSequence GetTransformationFormatted(Java.Lang.ICharSequence source, View view)
{
return new PasswordCharSequence(source);
}
}
private class PasswordCharSequence : Java.Lang.Object, Java.Lang.ICharSequence
{
private char DOT = '\u2022';
private Java.Lang.ICharSequence _source;
public PasswordCharSequence(Java.Lang.ICharSequence source)
{
_source = source;
}
public char CharAt(int index)
{
return _source.CharAt(index);
}
public int Length()
{
return _source.Length();
}
public Java.Lang.ICharSequence SubSequenceFormatted(int start, int end)
{
return _source.SubSequenceFormatted(start, end); // Return default
}
public IEnumerator<char> GetEnumerator()
{
return _source.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _source.GetEnumerator();
}
}
From code:
et.setInputType(InputType.TYPE_CLASS_NUMBER)

Categories

Resources