2

I have a small trick on how to restrict the number of characters in an edit text in android..for example I want to put a limit say 10 characters for the name field, so it will not allow the user to enter more than 10 characters.

Also, I have another problem in specifying the inputtype for text, I know the procedure which is android:inputType="text|textPersonName" but it dosen't work since it allows the user to enter characters, numbers and also special characters.

I will much appreciate your help.

Thanks in advance

Aditya Vyas-Lakhan
  • 13,409
  • 16
  • 61
  • 96
ZiZo
  • 61
  • 1
  • 3
  • 7

7 Answers7

10

Use following xml attributes to set maximum characters and digits to allow

android:digits
android:maxLength

For ex:

<EditText
android:id="@+id/et_name"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:digits="abcdefghijklmnopqrstuvwxyz ."
android:maxLength="10" />

Here, This allows only lower case alphabets, space and dot (.)

Upate

set filter by java

InputFilter myFilter = new InputFilter() { 
        public CharSequence filter(CharSequence source, int start, int end, 
Spanned dest, int dstart, int dend) { 
                for (int i = start; i < end; i++) { 


                        if (!Character.isLetter(source.charAt(i))) { 
                                return ""; 
                        } 

                        if (i == start) {
                           return source.toUpperCase();
                        }

                } 
                return source; 
        } 
}; 

edit.setFilters(new InputFilter[]{myFilter}); 
Jayabal
  • 3,619
  • 3
  • 24
  • 32
  • Oh it works well with digits attribute, but is there a way to make the first letter uppercase and the rest lower? – ZiZo Oct 06 '12 at 17:04
  • its not possible to do in xml, you've set filter, see updated answer. – Jayabal Oct 07 '12 at 02:57
  • I did wat you've said but I got an error in return source.toUpperCase; the error under toUpperCase – ZiZo Oct 07 '12 at 15:19
  • check updated ans. use source.toUpperCase(); instead of source.toUpperCase;, if again returns any error post error log – Jayabal Oct 15 '12 at 05:25
  • @ZiZo use `source.toString().toUpperCase();` as source is a `CharSequence` type and `toUpperCase()` is accessable for `String` type values. – Zubair Ahmed Jul 31 '15 at 06:18
3
android:maxLength="10"

This worked for me.

Harish Rana
  • 484
  • 3
  • 8
1

Try this:

android:maxLength="10"

in EditText in XML file.

pb2q
  • 58,613
  • 19
  • 146
  • 147
Chirag
  • 56,621
  • 29
  • 151
  • 198
  • thx so much this is worked perfectly. But how about the input type text, do you have any idea how to solve it? – ZiZo Oct 06 '12 at 13:44
1

For the first part what you have to do is write:

android:maxLength="10"

as far as your second question is concerned writing only textPersonName is sufficient

android:inputType="textPersonName" 

as referenced here input type

You have to use bit flags only when doing it programaticaly,which would correspond to:

 setInputType(InputType.TYPE_CLASS_TEXT  | InputType. TYPE_TEXT_VARIATION_PERSON_NAME);
sokie
  • 1,966
  • 22
  • 37
  • i think it is enough to modify your xml to android:inputType="textPersonName" it is really not necesary to do it by code – sokie Oct 06 '12 at 14:28
  • if you really want to do it by code,you have to do it after you get your edittext from the xml: EditText editText = (EditText) findViewById(R.id.yourEditText); editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType. TYPE_TEXT_VARIATION_PERSON_NAME); – sokie Oct 06 '12 at 14:30
  • when I do it using this attribute android:inputType="textPersonName" when the emulato runs it allows the user to enter alphabets, numbers and special characters. But when I d it using th line of code that you provided I got an error in the second line which is editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType. TYPE_TEXT_VARIATION_PERSON_NAME); a red line under setInputType, "|" and "." – ZiZo Oct 06 '12 at 16:17
1

For setting the restriction on the number of characters you should use as already posted

android:maxLength="10"

in the EditText in XML File. And if you want the user to restrict to only alphabets then you will have to create a custom input filter in JAVA code as follows

InputFilter filter = new InputFilter() { 
        public CharSequence filter(CharSequence source, int start, int end, 
Spanned dest, int dstart, int dend) { 
                for (int i = start; i < end; i++) { 
                        if (!Character.isLetter(source.charAt(i))) { 
                                return ""; 
                        } 
                } 
                return null; 
        } 
}; 

edit.setFilters(new InputFilter[]{filter}); 

Code taken from here.

Community
  • 1
  • 1
Antrromet
  • 15,294
  • 10
  • 60
  • 75
  • oh this is perfect but for the filter code where I have to put it in order to be applied only on the edit text of the person name? – ZiZo Oct 06 '12 at 14:06
  • In my last line edit.setFilters(new InputFilter[]{filter}); I am setting the filter to the EditText named edit. Similarly you put the filter on your EditText. – Antrromet Oct 06 '12 at 14:09
  • the error is syntax error on token "setFilters", = expected after this token – ZiZo Oct 06 '12 at 14:20
  • you need to write "edit.setFilters(new InputFilter[]{filter});" where "edit" is the name of your EditText. edit=(EditText)findViewById(R.id.editText1); edit.setFilters(new InputFilter[]{filter}); – Antrromet Oct 06 '12 at 16:48
  • ok it works well but it doesn't work with maxLength since it allows the user to enter as many as characters he wants. Any help? – ZiZo Oct 06 '12 at 18:08
  • If android:maxLength="10" does not work then again you could apply a custom filter. Look at this link http://stackoverflow.com/questions/3285412/limit-text-length-of-edittext-in-android – Antrromet Oct 07 '12 at 04:01
  • this is the xml – ZiZo Oct 07 '12 at 15:49
  • and this is the main.java InputFilter filter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (!Character.isLetter(source.charAt(i))) { return ""; } }return null; }}; edit=(EditText)findViewById(R.id.edittext1); edit.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(5)}); – ZiZo Oct 07 '12 at 15:51
  • but I need the first letter to be uppercase. Could you help me? – ZiZo Oct 07 '12 at 15:52
  • Use this in your xml android:inputType="textCapSentences" or android:capitalize="sentences". – Antrromet Oct 07 '12 at 16:46
1

Only 7, 8 ,9 digits start in Mobile number first character in android Working

Source Code

https://drive.google.com/open?id=0BzBKpZ4nzNzUQkU3S25fcXV4cEE

First Letter Start with 7,8,9 in Edit text in android

package com.keshav.mobilenumberrestriction_1_6_digits;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextWatcher;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    EditText et_mobile_feedback;
    String blockCharacterSet = "1234560";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et_mobile_feedback = (EditText) findViewById(R.id.et_mobile_feedback);

        et_mobile_feedback.setFilters(new InputFilter[] { filter });

        et_mobile_feedback.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
                // you can call or do what you want with your EditText here
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(et_mobile_feedback.getText().toString().length()==0)
                    blockCharacterSet="1234560";
                else
                    blockCharacterSet="";
                if(et_mobile_feedback.getText().toString().length()==10)
                    blockCharacterSet="1234567890";
            }
        });
    }
    private InputFilter filter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            try {
                if (source != null && blockCharacterSet.contains("" + source.charAt(0))) {
                    return "";
                }
            }catch (StringIndexOutOfBoundsException e){

            }
            return null;
        }
    };
}

    <EditText
        android:id="@+id/et_mobile_feedback"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:editable="true"
        android:fontFamily="sans-serif"
        android:gravity="top"
        android:hint="Mobile"
        android:textColor="@color/colorPrimary"
        android:inputType="number"
        android:maxLength="10"
        android:padding="15dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="10dp"
        android:singleLine="true">
Keshav Gera
  • 10,807
  • 1
  • 75
  • 53
1

it simple way in xml:

if u require to set 4 character in edit-text so,use this

android:maxLength="4"
Navadip Patel
  • 260
  • 4
  • 13