1.Android之TextView控制元件學習筆記
TextView控制元件學習
1 建立TextView物件有兩種方法:
1.1 在程式中建立TextView物件;
TextView tv=new TextView(this);
tv.setText("您好");
setContentView(tv);
1.2 在XML佈局檔案中使用;(推薦使用這種方法)
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="你好"
/>
設定字型的大小通常推薦使用sp作為單位。
設定寬度或者高度屬性時使用 dip作為單位。
2 dp sp和px的區別:
dp也就是dip,和sp基本類似,如果設定表示長度、高度、等屬性時可以使用dp或者sp。但是如果設定字型時,需要使用sp。dp是與密度無關的,sp除了與密度無關,還與scale無關。如果螢幕密度為160,這時dp和sp和px是一樣的。1dp=1sp=1px。但是如果使用px作單位,如果螢幕大小不變,而螢幕密度變成了320.那麼原來 TextView的寬度設成160px,在密度為320的3.2寸螢幕裡看要比在密度為160的3.2寸螢幕上看短了一半。但如果設定成160dp或者160sp的話,系統會自動將width屬性值設定成320px。也就是160*320/160。其中320/160可稱為密度比例因子,也就是說,如果使用dp或者sp,系統會根據螢幕密度的變化自動進行轉換。
px:表示螢幕實際的畫素。
3 設定字型顏色方法
3.1 android:textColor="#00FF00"
3.2
TextView tv=(TextView)findViewById(R.id.tv);
tv.setText(Html.fromHtml("<font color=blue>我的Android</fon>開發學習筆記"));
上述程式碼可以改變TextView控制元件中區域性文字的顏色。
3.3
String str="歡迎大家學習Android開發";
SpannableStringBuilder style=new SpannableStringBuilder(str);
style.setSpan(new ForegroundColorSpan(Color.RED),0,6,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(newForegroundColorSpan(Color.GREEN),6,13,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
style.setSpan(new ForegroundColorSpan(Color.BLUE),13,15,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
tv.setText(style);
4 設定超連結:
android:autoLink設定是否當文字為URL連結/email/電話/map時,文字顯示為可點選的連結。
android:autoLink="all"
5 跑馬燈效果
android:ellipsize設定當文字過長時,該控制元件該如何顯示。有如下值設定
“start”----省略號顯示在開頭。
“end” ----省略號顯示在結尾。
“middle”----省略號顯示在中間。
“marquee”-----以跑馬燈的方式現實。
當設定為marquee時,android:marqueeRepeatLimit設定重複滾動的次數,當設定為 marquee_forever時表示無限次。android:focusableInTouchMode:是否在觸控模式下獲得焦點。android:focusable控制元件是否能夠獲取焦點。
例項:<TextView
android:id="@+id/tv"
android:autoLink="all"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:textSize="20sp"
android:textColor="#00FF00"
android:focusable="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusableInTouchMode="true"
android:text="歡迎大家學習Android開發。我的部落格地址:http://blog.csdn.net/donggua199925我的電話15823008888"
/>