如何在 Android 的 EditText 中验证 URL/网站名称? [英] how to validate a URL / website name in EditText in Android?

查看:31
本文介绍了如何在 Android 的 EditText 中验证 URL/网站名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 Android 中的 EditText 获取输入、URL 或网站名称,例如 www.google.com,然后用户点击 按钮 提交或当 EditText 失去焦点时,应验证 URL,就像它的格式www.anyURL.com"...

I want to take input, a URL or just a website name like, www.google.com from EditText in Android and on user click on the Button to submit or when the EditText looses the focus the URL should be validated, like it is in the format "www.anyURL.com"...

我该怎么做?android 中是否有任何可用的内置功能?

How can I do this? Is there any inbuilt functionality available in android?

推荐答案

简短回答

在 Patterns 类中使用 WEB_URL 模式

Short answer

Use WEB_URL pattern in Patterns Class

 Patterns.WEB_URL.matcher(potentialUrl).matches()

如果 URL 有效则返回真如果 URL 无效则返回假.

从 Android API 级别 8 开始,有一个 WEB_URL图案.引用来源,它匹配 [es] RFC 3987 的大部分内容".如果您的目标是较低的 API 级别,您可以简单地从源复制模式并将其包含在您的应用程序中.我假设您知道如何使用模式和匹配器,所以我不会在这里详细介绍.

As of Android API level 8 there is a WEB_URL pattern. Quoting the source, it "match[es] most part of RFC 3987". If you target a lower API level you could simply copy the pattern from the source and include it in your application. I assume you know how to use patterns and matchers, so I'm not going into more details here.

此外,URLUtil 类还提供了一些有用的方法,例如:

Also the class URLUtil provides some useful methods, e.g:

方法的描述不是很详细,因此您最好查看来源并找出最适合您的目的.

The descriptions of the methods are not very elaborate, therefore you are probably best of looking at the source and figuring out which one fits your purpose best.

关于何时触发验证检查,有多种可能:您可以使用 EditText 回调函数

As for when to trigger the validation check, there are multiple possibilities: you could use the EditText callback functions

或使用 TextWatcher,我认为这样会更好.

or use a TextWatcher, which I think would be better.

请勿使用 URLUtil 验证 URL,如下所示.

DON'T USE URLUtil to validate the URL as below.

 URLUtil.isValidUrl(url)

因为它给出了像http://"这样的字符串.作为不正确的有效 URL

because it gives strings like "http://" as valid URL which isn't true

这篇关于如何在 Android 的 EditText 中验证 URL/网站名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆