TextView設定字型樣式

來源:互聯網
上載者:User

 

TextView是用來顯示文本的,有時需要給TextView中的個別字設定為超連結,或者設定個別字的顏色、字型等,那就需要用到Spannable對象,可以藉助Spannable對象實現以上設定。

Activity代碼:

  1. package com.zhou.activity;
  2. import android.app.Activity;
  3. import android.graphics.Color;
  4. import android.os.Bundle;
  5. import android.text.Spannable;
  6. import android.text.SpannableString;
  7. import android.text.Spanned;
  8. import android.text.method.LinkMovementMethod;
  9. import android.text.style.BackgroundColorSpan;
  10. import android.text.style.ForegroundColorSpan;
  11. import android.text.style.StyleSpan;
  12. import android.text.style.URLSpan;
  13. import android.widget.TextView;
  14. public class TextViewLinkActivity extends Activity {
  15. TextView myTextView;
  16. @Override
  17. public void onCreate(Bundle savedInstanceState) {
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.main);
  20. myTextView = (TextView) this.findViewById(R.id.myTextView);
  21. //建立一個 SpannableString對象
  22. SpannableString sp = new SpannableString("這句話中有百度超連結,有高亮顯示,這樣,或者這樣,還有斜體.");
  23. //設定超連結
  24. sp.setSpan(new URLSpan("http://www.baidu.com"), 5, 7,
  25. Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  26. //設定高亮樣式一
  27. sp.setSpan(new BackgroundColorSpan(Color.RED), 17 ,19,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
  28. //設定高亮樣式二
  29. sp.setSpan(new ForegroundColorSpan(Color.YELLOW),20,24,Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
  30. //設定斜體
  31. sp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 27, 29, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
  32. //SpannableString對象設定給TextView
  33. myTextView.setText(sp);
  34. //設定TextView可點擊
  35. myTextView.setMovementMethod(LinkMovementMethod.getInstance());
  36. }
  37. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.