【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)