Android開發技巧三--格式化TextView文本

來源:互聯網
上載者:User

標籤:android   textview   格式化   

本例主要研究一下如何在TextView中顯示網頁連結和改變特定文字顏色

1.main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/tv_url"        android:layout_width="wrap_content"        android:layout_height="wrap_content" />    <TextView        android:id="@+id/tv_color"        android:layout_width="wrap_content"        android:layout_height="wrap_content"         android:text="HelloWorld,HomeActivity!"/>    </LinearLayout>

2.MainActivity.java:

package com.yayun.edittextdatedemo;import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.text.Html;import android.text.Spannable;import android.text.SpannableString;import android.text.method.LinkMovementMethod;import android.text.style.BackgroundColorSpan;import android.text.style.ForegroundColorSpan;import android.widget.TextView;public class MainActivity extends Activity {private TextView mTextView1;private TextView mTextView2;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mTextView1=(TextView) findViewById(R.id.tv_url);mTextView2=(TextView) findViewById(R.id.tv_color);String text="Visit <a href=\"http://www.baidu.com\">百度網</a>";mTextView1.setText(Html.fromHtml(text));//以連結的形式顯示mTextView1.setMovementMethod(LinkMovementMethod.getInstance());//在單擊連結時凡是要執行的動作,都必須設定MovementMethod對象Spannable sTextSpannable=new SpannableString(mTextView2.getText());sTextSpannable.setSpan(new BackgroundColorSpan(Color.RED),1,4,0);//spannableString.setSpan(backgroundColorSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);sTextSpannable.setSpan(new ForegroundColorSpan(Color.BLUE),5,9,0);mTextView2.setText(sTextSpannable);}}

3.運行執行個體:


總結

1.Html.fromHtml(text),將文本轉成html形式;

2.mTextView1.setMovementMethod(LinkMovementMethod.getInstance());//在單擊連結時凡是要執行的動作,都必須設定MovementMethod對象

3.sTextSpannable.setSpan(new BackgroundColorSpan(Color.RED),1,4,0);//spannableString.setSpan(backgroundColorSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

Android開發技巧三--格式化TextView文本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.