Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaAutoCompleteTextView.Validator in Android with Example

AutoCompleteTextView.Validator in Android with Example

AutoCompleteTextView is an EditText which is having features of suggesting what to write next . to show suggestions it uses a drop-down that can be canceled by the back press. Each time, when we use an android application, suppose the user has to write names for multiple places, it will increase the time of the user. For reducing the time and increasing the smoothness of the application user we use AutoCompleteTextView. 

What is AutoCompleteTextView.Validator ?

As we discussed above, to validate the suggested text we use AutoCompleteTextView.Validator. A sample video is given below to get an idea about what we are going to do in this article.

Note: This Android article covered in both Java and Kotlin languages. 

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Working with the activity_main.xml file

Navigate to app > res > layout > activity_main.xml and add the below code to it. Comments are added in the code to get to know in detail. 

XML




<!-- XML code -->
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    tools:context=".MainActivity">
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
  
        <AutoCompleteTextView
            android:id="@+id/autoCompleteTextView"
            android:layout_width="match_parent"
            android:layout_height="100px"
            android:textColor="@android:color/holo_green_light"
            android:textSize="20sp"
            android:backgroundTint="#8C8B8B"
            android:textAlignment="center"
            android:layout_gravity="center"
            android:hint="gfg"/>
  
        <EditText
            android:id="@+id/editTextTextPersonName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="textPersonName"
            android:textColor="#5fb300"
            android:textAlignment="center"
            android:layout_gravity="center"
            android:text="focus on me to validate" />
  
    </LinearLayout>
    
</androidx.constraintlayout.widget.ConstraintLayout>


Step 3: Working with the MainActivity file 

Navigate to app > java > your app’s package name > MainActivity file and add the below code to it. Comments are added in the code to get to know in detail. 

Java




package com.example.gfgvalidator;
  
import static android.widget.Toast.LENGTH_SHORT;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Arrays;
  
public class MainActivity extends AppCompatActivity {
      
    // string values for drop down suggestions
    String[] countries={"India","Japan","West indies","indonesia","Indiana",
            "South Asia","Englishtan","Srilanka",};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // creating adapters 
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,countries);
          
        // assigning ID's
        AutoCompleteTextView textView=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView);
          
        // setting threshold to 1, so that start
        // suggesting by match only first letter
        textView.setThreshold(1);
        textView.setAdapter(adapter);
  
        // using setvalidator
        textView.setValidator(new AutoCompleteTextView.Validator() {
            @Override
            public boolean isValid (CharSequence text){
                Log.v("Test", "Checking if valid: "+ text);
                Arrays.sort(countries);
                if (Arrays.binarySearch(countries, text.toString())>0) {
                    Toast.makeText(MainActivity.this, "Correct", LENGTH_SHORT).show();
                    return true;
                }
                return false;
            }
  
            @Override
            public CharSequence fixText (CharSequence invalidText){
                // If .isValid() returns false then the code comes here
                // do whatever way you want to fix in the 
                // users input and  return it
                return "wrong input please correct";
            }
        });
  
        // for changing the background color of title bar
        ActionBar aBar = getSupportActionBar();
        ColorDrawable cd = new ColorDrawable(Color.parseColor("#FF00FF00"));
        if (aBar != null) {
            aBar.setBackgroundDrawable(cd);
        }
    }
  
    // using focus change listener 
    class FocusListener implements View.OnFocusChangeListener {
  
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (v.getId() == R.id.autoCompleteTextView && !hasFocus) {
                ((AutoCompleteTextView)v).performValidation();
            }
        }
    }
  
}


Kotlin




package com.example.gfgvalidator;
  
import static android.widget.Toast.LENGTH_SHORT;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Arrays;
  
class MainActivity : AppCompatActivity() {
    // string values for drop down suggestions
    var countries = arrayOf(
        "India", "Japan", "West indies", "indonesia", "Indiana",
        "South Asia", "Englishtan", "Srilanka"
    )
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // creating adapters
        val adapter = ArrayAdapter(this, R.layout.simple_dropdown_item_1line, countries)
          
        // assigning ID's
        val textView = findViewById<View>(R.id.autoCompleteTextView) as AutoCompleteTextView
          
        // setting threshold to 1 , so that start 
        // suggesting by match only first letter
        textView.threshold = 1
        textView.setAdapter(adapter)
  
        // using setvalidator
        textView.validator = object : AutoCompleteTextView.Validator {
            override fun isValid(text: CharSequence): Boolean {
                Log.v("Test", "Checking if valid: $text")
                Arrays.sort(countries)
                if (Arrays.binarySearch(countries, text.toString()) > 0) {
                    Toast.makeText(this@MainActivity, "Correct", Toast.LENGTH_SHORT).show()
                    return true
                }
                return false
            }
  
            override fun fixText(invalidText: CharSequence): CharSequence {
                // If .isValid() returns false then the code comes here
                // do whatever way you want to fix in 
                // the users input and  return it
                return "wrong input please correct"
            }
        }
  
        // for changing the background 
        // color of title bar
        val aBar = supportActionBar
        val cd = ColorDrawable(Color.parseColor("#FF00FF00"))
        aBar?.setBackgroundDrawable(cd)
    }
  
    // using focus change listener
    internal class FocusListener : OnFocusChangeListener {
        override fun onFocusChange(v: View, hasFocus: Boolean) {
            if (v.id == R.id.autoCompleteTextView && !hasFocus) {
                (v as AutoCompleteTextView).performValidation()
            }
        }
    }
  
}


Output:

RELATED ARTICLES

Most Popular

Recent Comments