dev90
dev90

Reputation: 7529

How to get the Name of View in Java Class

I have a class, I am passing EditText to it. There are more than 10 EditBox in my activity, I pass each to my class. In my class i need to add conditions based on the name of EditBox; For example,

if EditBox is of Address type, then i need to user to enter at least 5 characters in the EditBox

if EditBox is of Name type, then i need to user to enter at least 7 characters in the EditBox

So i need to know the name of EditBox in my class, Kindly tell me a way to get name of EditBox in Java Class

  formTextCosmetics.validateInputFields(etName, ivWarningCardName);

  formTextCosmetics.validateInputFields(etAddress, ivWarningAddress);

Java Class

     public void validateInputFields(final EditText editText, final ImageView imageView){

            editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus){
                if(editText.getText().toString().trim().length() ==0){
                //Here i need to check the name of editText

Upvotes: 0

Views: 154

Answers (1)

Imran Ali
Imran Ali

Reputation: 321

Why not just add validations in XML file.

<EditText      
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "
android:maxLength="30"
android:inputType="text"
android:maxLine="1"
/>

You can also use a textwatcher to check min and max length.

public void afterTextChanged(Editable s) {
     int length= s.getText.ToString().Trim().Length();
     if (length<5){
     s.setError("Any message")
}
}

Upvotes: 2

Related Questions