android textView 添加超鏈接(兩種實現方式)


在textView添加超鏈接,有兩種方式,第一種通過HTML格式化你的網址,一種是設置autolink,讓系統自動識別超鏈接,下面為大家介紹下這兩種方法的實現

在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 href='http://www.baidu.com'>百度一下</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不僅 識別超鏈接,包括電話號碼之類的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM