在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不僅 識別超鏈接,包括電話號碼之類的。