Android TextView 添加超鏈接的兩種實現方式
在textView添加超鏈接,有兩種方式,第一種通過HTML格式化你的網址,一種是設置autolink,讓系統自動識別超鏈接,下面為大家介紹下這兩種方法的實現
代碼如下:
第一種
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
TextView textView = new TextView(this);
String html = "有問題:\n";
html+="<a ;//注意這里必須加上協議號,即http://。
//否則,系統會以為該鏈接是activity,而實際這個activity不存在,程序就崩潰。
CharSequence charSequence = Html.fromHtml(html);
textView.setText(charSequence);
textView.setMovementMethod(LinkMovementMethod.getInstance());
layout.addView(textView);
this.setContentView(layout,params);
}
第二種
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout(this);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
TextView textView = new TextView(this);
String html = "有問題:\n";
html+="www.baidu.com";//這里即使不加協議好HTTP;也能自動被系統識別出來。
textView.setText(html);
textView.setAutoLinkMask(Linkify.ALL);
textView.setMovementMethod(LinkMovementMethod.getInstance());
layout.addView(textView);
this.setContentView(layout,params);
}
總結一下就是,以html顯示超鏈接,必須寫全url。以setAutoLinkMask(Linkify.ALL)可以不用不用寫全,就能自動識別出來。
這兩種方法,都得設置一下setMovementMethod,才會跳轉。
另外setAutoLinkMask不僅 識別超鏈接,包括電話號碼之類的。
本文由用戶 TerryPumpki 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!