【Android的從零單排開發日記】之入門篇(十五)——TextView+SpannableStringBuilder,androidtextview

來源:互聯網
上載者:User

【Android的從零單排開發日記】之入門篇(十五)——TextView+SpannableStringBuilder,androidtextview

TextView是控制項中最最基礎的一個控制項,也是最簡單的一個控制項。但如果僅此,我不會專門為TextView寫一篇文章。最近發現了Android中有趣的一個類,那就是標題上寫的SpannableStringBuilder。那麼它是個什麼東西呢?它可以為你的文字加上各種效果,像變色,各種符號,斜體,圖片替換,高亮等等。如果想要文字加上一點常見的效果,我們大可不必再自己去寫一個自訂的View,使用SpannableStringBuilder就能滿足你的需求了。

 

一、TextView

首先是TextView的準備,跟平常的一樣,先在布局檔案中寫好控制項,再在代碼中通過id獲得引用。

<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/textView1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/text_view" />    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/button" /></LinearLayout>

 

@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);        tv = (TextView)findViewById(R.id.textView1);    bt = (Button)findViewById(R.id.button1);    bt.setOnClickListener(this);    }

二、SpannableStringBuilder

SpannableStringBuilder其實講白了就是一個文字編輯器,通過套用不同的模式來改變文本的樣子,其主要方法為

    /**     * Mark the specified range of text with the specified object.     * The flags determine how the span will behave when text is     * inserted at the start or end of the span's range.     */    public void setSpan(Object what, int start, int end, int flags) {        setSpan(true, what, start, end, flags);    }

 

第一個參數是一個實現ParcelableSpan介面的一個類;

第二三個參數就是要改變文本的位置,起始點和終點;

第四個參數是用來對第二個和第三個參數進一步限制和說明的。

 

三、文本的例子

 

四、結束語

說來慚愧,好久沒有更新這個系列了,也是一直沒有機會弄Android介面的原因。今天看到一個文字變化的工具類,所以就想著把TextView做了一下。

  

========================================

 

作者:cpacm
出處:(http://www.cnblogs.com/cpacm/p/4099031.html)

聯繫我們

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