如何验证URL /网站名称的EditText在Android中?名称、网站、URL、EditText

2023-09-12 02:52:30 作者:欲情故纵

我想借此输入URL或只是一个网站的名字一样,www.google.com从的EditText在Android和对userclick按钮提交或者当的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 userclick 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"...

我怎样才能做到这一点?没有任何内在的功能,可以在机器人?

How can i do this? is there any inbuilt functionality available in android?

推荐答案

在模式类使用的web_url模式

Short answer

Use WEB_URL pattern in Patterns Class

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

这将返回真,如果URL是有效和假的如果URL无效

由于Android的API级别8有一个的web_url 模式。引用来源,它符合[西]最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:

isHttpUrl() isValidUrl() isHttpUrl() isValidUrl()

方法的描述都不是很复杂的,因此,你可能是最好的查看源,并找出哪一个最适合你的目的。

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

onFocusChanged(),或 onTextChanged() onFocusChanged(), or onTextChanged()

或使用 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