0

Edit Text Validation In Android Example ~ Codeofsandy

Today i am going to share Android Validation on EditText
setError() is used to show the error.

Android EditText Validation Example

main.xml
[code language=”css”]

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">

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

<Button
android:layout_height="wrap_content"
android:id="@+id/button1"
android:text="Check"
android:layout_width="wrap_content"
android:onClick="btnClick">
</Button>

</LinearLayout>

[/code]

MainActivity.java

[code language=”css”]

package code.of.sandy

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

/**
*
* @author Sandy
* Purpose: Demo to show the purpose of setError() method in EditText view.
*
*/
public class MainActivity extends Activity {
/** Called when the activity is first created. */

EditText editText;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

editText = (EditText) findViewById(R.id.editText1);
}

public void btnClick(View v)
{
if(editText.getText().length()==0)
{
editText.setError("Field cannot be left blank");
}
}
}
[/code]

Sandeep Kumar

Sandeep kumar is a web developer and a professinal blogger. He works for latest technologies and write articles what he learn. In ICodeHub he share web languages tutorials and other programming tips and tricks. if you need some help or have some suggestion then mail him at sandeep92pal@gmail.com without any hesitation. He believes in learning and sharing.