Set maxlength for edittext in android programmatically

Get Max length input setting on application run time.

EditText max length represents here maximum length of edittext input in characters format. For example app developer can set restrictions to app user so application user cannot enable to enter more then specify characters limit. So here is the complete step by step tutorial for Set maxlength for edittext in android programmatically.

android-project-download-code-button

How to Set maxlength for edittext in android programmatically. 

Code for MainActivity.java file.

 package com.edittextmaxlength_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

 EditText edtext;
 Button MaxLenth;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 edtext = (EditText)findViewById(R.id.editText1);
 MaxLenth = (Button)findViewById(R.id.button1);
 
 MaxLenth.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 
 edtext.setFilters(new InputFilter[] { new InputFilter.LengthFilter(7) });
 
 }
 });
 
 
 }
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.edittextmaxlength_android_examples.com.MainActivity" >

 <EditText
 android:id="@+id/editText1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:ems="10" >

 <requestFocus />
 </EditText>

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/editText1"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="18dp"
 android:text="Click Here to set Max Lenth as 7" />

</RelativeLayout>

Screenshots:

Set maxlength for edittext in android programmatically

Click Here to download Set maxlength for edittext in android programmatically project.

Leave a Reply

Your email address will not be published. Required fields are marked *