How to show error in an EditText using setError() in Android?

By | September 13, 2012

We will go straight to the code.

package com.coderzheaven.seterror;

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

public class MainActivity extends Activity {

	 @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.activity_main);
	        Button btn =(Button)findViewById(R.id.button1);
	        btn.setOnClickListener(new OnClickListener() {
	            
	            @Override
	            public void onClick(View v) {
	                 EditText edittext =(EditText)findViewById(R.id.editText1);
	                if(edittext.getText().length()==0){
	                    edittext.setError("Field cannot be left blank.");
	                }
	            }
	        });
	    }
}

This is the layout containing the EditText and the Button.

<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" >

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

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/editText1"
        android:text="Check" />

</RelativeLayout>

SetError Android

2 thoughts on “How to show error in an EditText using setError() in Android?

  1. Pingback: How to show error in an EditText using setError() in Android? » Ideal Codes

  2. Pingback: Text watcher in Android

Leave a Reply

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