In this article, we are going to set restrictions in our EditText for URL. Whenever we are creating any form and we want to get the portfolio website of the user or even if we want to restrict the user to write the only URL then we can use this feature. This enables a user to user to write URL only.
Step By Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. We will create a simple EditText in this file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < LinearLayout android:layout_width = "match_parent" android:layout_height = "match_parent" android:gravity = "center" android:orientation = "vertical" tools:context = ".MainActivity" > < EditText android:id = "@+id/aurl" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:hint = "Enter Url" /> </ LinearLayout > |
Step 3: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Patterns; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { EditText addurl; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); addurl = findViewById(R.id.aurl); // when we add text in the edit text // it will check for the pattern of text addurl.addTextChangedListener( new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } // whenever text size changes it will check @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // if text written matches the pattern then // it will show a toast of pattern matches if (Patterns.WEB_URL.matcher(addurl.getText().toString()).matches()) { Toast.makeText(MainActivity. this , "Pattern Matches" , Toast.LENGTH_SHORT).show(); } else { // otherwise show error of invalid url addurl.setError( "Invalid Url" ); } } @Override public void afterTextChanged(Editable s) { } }); } } |
Output: