1. 程式人生 > >Android textView屬性設定超連結

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 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);
}

第三種

strings.xml中定義字串

<string name="blog"><a href="http://blog.csdn.net/jonahzheng">東子的部落格</a></string>

佈局中textview定義,並且textview的text引用stings.xml中定義的‘blog’

    <TextView
    android:id="@+id/tv_blog"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
android:layout_marginTop="10dp" android:text="@string/blog" android:textColor="#F5F5F5" android:textSize="18sp" />

java程式碼中

加入

[java] view plaincopyprint?
  1. TextView tv_blog =(TextView) findViewById(R.id.tv_blog);
  2. <pre><code class="avrasm"></code><pre name="code"class="java">tv_blog.setMovementMethod(LinkMovementMethod<span class="preprocessor">.getInstance</span>())<span class="comment">;</span></pre>  
  3. <pre></pre>  
  4. <pre></pre>  
  5. <p></p>  
  6. </pre>
總結一下就是,以html顯示超連結,必須寫全url。以setAutoLinkMask(Linkify.ALL)可以不用不用寫全,就能自動識別出來。

這幾種方法,都得設定一下setMovementMethod,才會跳轉。
另外setAutoLinkMask不僅 識別超連結,包括電話號碼之類的。