SetError method in EditText box

Today we are going to implement set error method for edittext.It is useful for diaplaying message if  user enters something wrong or leave it blank.

MainActivity,java

package com.arjun.test;

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

public class MainActivity extends Activity {

EditText edtname;
Button btncheck;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtname =(EditText)findViewById(R.id.edtName);
btncheck = (Button)findViewById(R.id.btnCheck);
btncheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(edtname.getText().length() ==0)
{
edtname.setError("Please fill name...");
}
}
});
}


}



activity_main.xml

<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"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/edtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="47dp"
        android:layout_marginTop="28dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/btnCheck"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edtname"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="76dp"
        android:text="Button" />

</RelativeLayout>


Output





Comments

Popular Posts