Android App开发中如何对一段文本添加超链接并且使得文本两端对齐
根据以上需求能想到的实现方式如下:
- 通过textview实现
- 通过webview实现
以下是具体的实现过程:
通过textview去实现
首先给textview添加超链接,并修改超链接中文本的颜色
这些需求textview自身已经提供了api供我们使用,代码如下:
Textview textview = new TextView(this);
String text = textview .getText().toString().trim();
SpannableString spannableString = new SpannableString(text);
spannableString .setSpan(0x516111, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString .setSpan(new UnderlineSpan(), startIndex, endIndex, , Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textview .setText(spannableString );
虽然以上方式可以满足我们的第一个需求,但是对于实现两端对齐textview自身并没有提供相应的api让我们去使用,这个时候就需要我们自己去重构textview的代码,当然网上也提供了实现该需求的一些代码,可以参考下面的链接: https://github.com/androiddevelop/AlignTextView
注:在完成上面工作后,我们会发现并不能满足我们的需求,两者只能选择其中之一去显示,这样以来通过textview去实现就有些行不通。那我们只能选择后者去实现了
通过webview去实现
主要有两个步骤:
- 定义自己html文件(需要一点html基础)
- 通过webview加载定义好的html文件
下面是详细过程
1.生成html文件
/**
*source :我们要展示的文本内容
*/
private String formatHtml(String source) {
if (!TextUtils.isEmpty(source) && source.indexOf("http") != -1) {
String link = source.substring(source.indexOf("http"), source.indexOf("html") + 4);
String startContent = source.substring(0, source.indexOf("http"));
String endContent = source.substring(source.indexOf("html") + 4);
link = "<a style=\"color:blue;\" href=\"" + link + "\">" + link + "</a>";
source = startContent + link + endContent;
}
source = String.format("<div id=\"webview_content_wrapper\">%s</div>", source);
String content =
"<html>"
+ "<head>\n"
+ "<style type=\"text/css\">body{}</style>"
+ "</head>"
+ "<body style=\"font-family:arial;color:white;font-size:22px;text-align:justify\">"
+ "<script type='text/javascript'> window.onload = function(){\n"
+ "var $img = document.getElementsByTagName('img');\n"
+ "for(var p in $img){\n"
+ "if($img[p].width > " + width + " ) { \n"
+ "$img[p].style.width = '100%';\n"
+ "$img[p].style.height = 'auto'}}}"
+ "</script>"
+ "<p>" + source + "</p>"
+ "</body>"
+ "</html>";
return content;
}
2.加载
if (webView!= null) {
webView.loadData( formatHtml(text), "text/html; charset=UTF-8", null);
}
注:在这里为什么我没有使用下面的api去加载显示,原因为使用它会导致页面数据没有实时更新,我怀疑可能是加载缓存数据,具体原因没有找到,因为在这里花了时间,最后也是无奈才选择loadData()去加载,没想到还成功了
webView.loadDataWithBaseURL(params);