Monday, 6 October 2014

how to set edittext error message in android


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="20dp"
    android:orientation="vertical" >

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

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Password" />

    <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Loging" />

</LinearLayout>


MainActivity.java

package com.test;

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

public class MainActivity extends Activity {

   
    private EditText edit_username,edit_password;
    private Button btn_login;
   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        edit_username=(EditText)findViewById(R.id.editText1);
        edit_password=(EditText)findViewById(R.id.editText2);
       
        btn_login=(Button)findViewById(R.id.button1);
        btn_login.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
               
                if(Validation()){
                   
                    Toast.makeText(getApplicationContext(), "login Success", Toast.LENGTH_LONG).show();
                }
               
            }
        });
    }
   
    private boolean Validation(){
       
        // Checking If Selected Values is Default
        if (edit_username.getText().toString().equals("")) {
            edit_username.setError(Html.fromHtml("<font color='red'>Enter the Username</font>"));
            return false;
        }
       
        if (edit_password.getText().toString().equals("")) {
            edit_password.setError(Html.fromHtml("<font color='red'>Enter the Password</font>"));
            return false;
        }
        return true;
       
    }

}






No comments:

Post a Comment