Skip to content
Related Articles

Related Articles

How to Set Restriction For URL in Android EditText?

Improve Article
Save Article
  • Last Updated : 18 Apr, 2021
Improve Article
Save Article

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 version="1.0" encoding="utf-8"?>
        android:hint="Enter Url" />

Step 3: Working with the file

Go to the file and refer to the following code. Below is the code for the file. Comments are added inside the code to understand the code in more detail.


import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Patterns;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    EditText addurl;
    protected void onCreate(Bundle savedInstanceState) {
        addurl = findViewById(;
        // when we add text in the edit text 
        // it will check for the pattern of text
        addurl.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // whenever text size changes it will check
            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");
            public void afterTextChanged(Editable s) {


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!