10

我怎么知道某些文本包含“http://www”。我想在 Web 视图中显示域。域名写在 TextView 中,但不限制添加前缀。如果用户没有输入它,我必须在 webview 中添加和显示 URL。

4

6 回答 6

27

你可以这样做

String url = textView.getText().toString();
if(!url.startsWith("www.")&& !url.startsWith("http://")){
  url = "www."+url;
}
if(!url.startsWith("http://")){
  url = "http://"+url;
}

您可以使用此 url 在 WebView 中显示内容

希望这能解决你的问题

于 2012-05-18T10:06:04.290 回答
5

刚刚修改了@silwar 答案并添加了 https :

 if(!url.startsWith("www.")&& !url.startsWith("http://") && !url.startsWith("https://")){
        url = "www."+url;
    }
    if(!url.startsWith("http://") && !url.startsWith("https://")){
        url = "http://"+url;
    }

但请记住,有时会http://在 android 中创建安全异常,因此我们应该使用https://. 所以对于无风险代码,我们必须像上次检查一样这样做 -

 if(!url.startsWith("http://") && !url.startsWith("https://")){
            url = "https://"+url;}
于 2015-07-20T08:35:45.583 回答
3

The most efficient way of checking that the domain name is well formed and contains (or not) a prefix, is using a regular expression.

Check out Java Pattern to match regex in Android. It is worth it.

于 2012-05-18T09:58:44.290 回答
2

正如 Sebastien 所要求的,正则表达式是一个不错的选择。您还可以从视图中获取文本,创建一个 URI 对象

Uri uri = Uri.create(view.getText().toString());

然后使用 uri.somemethod 您应该能够获得有关您想知道的 url 的所有信息。如果 uri 创建失败,您会生成错误消息,导致出现问题。

于 2012-05-18T10:01:56.807 回答
1

I would just get the text from the TextView and parse it via startsWith(). If this is false, just add it to the text and use setText() to reasign it.

You might also want to check for other expressions like only "www.". So take a closer look at contains().

于 2012-05-18T09:58:54.180 回答
-2

尝试这个

String a = "http://";
webview.loadUrl(a + url.getText().toString());
于 2013-04-18T15:12:51.413 回答