Saturday 17 March 2012

In Android how to show error in EditText

To display input error on in edit text .



















Create a main.xml layout with a EditText box and a Button.
Main.xml
<?xml version="1.0" encoding="utf-8"?>  
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    android:orientation="vertical" android:layout_width="fill_parent"  
    android:layout_height="fill_parent">  
        <EditText android:id="@+id/editText1" 
                           android:layout_height="wrap_content"  
                           android:layout_width="match_parent" 
                           android:hint="Username"  
       / >  
        <Button android:id="@+id/button1" 
                        android:text="Register for Push Notification"  
                        android:layout_height="wrap_content" 
                        android:layout_width="wrap_content"
                  android:onClick="ErrorCheck"
                  android:text="Test It !!"
        />  
</LinearLayout> 







Now write a method in your activity "ErrorCheck" that is declired in main.xml file on Button Click .To display error you just need to check the error condition and editText.setError("your error message");
public class MainActivity extends Activity { 
EditText editText;
@Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
        editText= (EditText) findViewById(R.id.editText1);
    }  
public void ErrorCheck(View v){
if(editText.getText().length()==0){
          editText.setError("Please input text");
        }
}
}






Enjoy.... 
Do post your doubts, queries or suggestions in this blog.

No comments:

Post a Comment