1. 程式人生 > >android基本控制元件-textview

android基本控制元件-textview

安卓應用是由許多控制元件組成的,這些控制元件都直接或間接繼承View類.就像微軟的winform程式一樣,這些控制元件也有一系列的事件機制.textview 就是非常常見的控制元件.用來顯示文字,個人感覺跟html中span比較類似.

textview可以使用android:autoLink 設定相應的屬性自動呼叫系統功能.需要設定好該控制元件的text屬性.比如說設定text屬性為電話號碼,或者網頁.該屬性的值會有以下幾種情況

  1. None:預設的,不匹配任何連線。
  2. web:表示跳轉網址
  3. phone:打電話
如下:    
<TextView
    android:id="@+id/tv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:autoLink="phone"
    android:text="13505344567" />


會跳轉到系統撥號介面
另外在java程式碼層,可以靈活設定textview的text屬性,加入一些html元素進去.程式碼如下:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv =(TextView) findViewById(R.id.tv);
    String html="<a href='http://baidu.com'>百度</a>";
    //使用Html.fromHtml,把含HTML標籤的字串轉換成可顯示的文字樣式
    CharSequence charSequence= Html.fromHtml(html);
    tv.setText(charSequence);
    //設定是否響應動作
    tv.setMovementMethod(LinkMovementMethod.getInstance());
}


同時利用SpannableString可以對設定到textview的文字進行切割,分別為單個文字設定樣式
TextView tv2 =(TextView) findViewById(R.id.tv2);
String text="我是最帥的";
SpannableString spannableString=new SpannableString(text);
BackgroundColorSpan colorSpan = new BackgroundColorSpan(Color.parseColor("#AC00FF30"));
//start和end分別指定需要響應onClick()方法的文字開始與結束。flags設定一個標識,確定使用什麼方式選擇文字塊,
// 一般使用Spanned介面下的SPAN_EXCLUSIVE_EXCLUSIVE對其進行賦值,表示遵循設定的開始於結束位置的文字塊。
spannableString.setSpan(colorSpan,0,1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv2.setText(spannableString);


結果如下圖
textview跑馬燈效果,程式碼如下:
<TextView
    android:id="@+id/tv4"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:background="#FFF"
    android:ellipsize="marquee"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:marqueeRepeatLimit="marquee_forever"
    android:padding="10dp"
    android:singleLine="true"
    android:textColor="#000"
    android:textSize="20dp"
    android:text="測試跑馬燈測試跑馬燈測試跑馬燈測試跑馬燈測試跑馬燈測試跑馬燈"
    />

關鍵是屬性設定:android:focusableInTouchMode,focusableInTouchMode,focusable屬性必須設定為true
常用屬性介紹:
ellipsize:表示文字溢位時的處理方式,類似於html中overflow屬性.常用值none(不隱藏)、start(隱藏開始)、middle(隱藏中間)、end(隱藏結束)、marquee(滾動效果)。
singleLine:表示單行顯示文字
android:drawableLeft在text的左邊輸出一個drawable,如圖片。 
android:gravity設定文字位置,如設定成“center”,文字將居中顯示
android:lines設定文字的行數,設定兩行就顯示兩行,即使第二行沒有資料。
android:textColor設定文字顏色 
android:textScaleX設定文字之間間隔,預設為1.0f。 
android:drawableRight在text的右邊輸出一個drawable。 
android:drawableTop在text的正上方輸出一個drawable。