學習完Android中的六大布局,從本節開始咱們來一個個講解Android中的UI控件,本節給你們帶來的UI控件是:TextView(文本框),用於顯示文本的一個控件,另外聲明一點,我不是翻譯API文檔,不會一個個屬性的去扣,只學實際開發中經常使用的,有用的,你們遇到感受到陌生的屬性能夠查詢對應的API!固然,每一節開始都會貼這一節對應API文檔的連接:TextView API 好了,在開始本節內容前,先要介紹下幾個單位:html
dp(dip): device independent pixels(設備獨立像素). 不一樣設備有不一樣的顯示效果,這個和設備硬件有關,通常咱們爲了支持WVGA、HVGA和QVGA 推薦使用這個,不依賴像素。 px: pixels(像素). 不一樣設備顯示效果相同,通常咱們HVGA表明320x480像素,這個用的比較多。 pt: point,是一個標準的長度單位,1pt=1/72英寸,用於印刷業,很是簡單易用; sp: scaled pixels(放大像素). 主要用於字體顯示best for textsize。android
經過下面這個簡單的界面,咱們來了解幾個最基本的屬性:web
佈局代碼:數組
<RelativeLayout 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" tools:context=".MainActivity" android:gravity="center" android:background="#8fffad"> <TextView android:id="@+id/txtOne" android:layout_width="200dp" android:layout_height="200dp" android:gravity="center" android:text="TextView(顯示框)" android:textColor="#EA5246" android:textStyle="bold|italic" android:background="#000000" android:textSize="18sp" /> </RelativeLayout>
上面的TextView中有下述幾個屬性:微信
涉及到的幾個屬性:app
效果圖:ide
實現代碼:佈局
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:shadowColor="#F9F900" android:shadowDx="10.0" android:shadowDy="10.0" android:shadowRadius="3.0" android:text="帶陰影的TextView" android:textColor="#4A4AFF" android:textSize="30sp" />
若是你想爲TextView設置一個邊框背景,普通矩形邊框或者圓角邊框!下面可能幫到你! 另外TextView是不少其餘控件的父類,好比Button,也能夠設置這樣的邊框! 實現原理很簡單,自行編寫一個ShapeDrawable的資源文件!而後TextView將blackgroung 設置爲這個drawable資源便可!性能
簡單說下shapeDrawable資源文件的幾個節點以及屬性:學習
- <solid android:color = "xxx"> 這個是設置背景顏色的
- <stroke android:width = "xdp" android:color="xxx"> 這個是設置邊框的粗細,以及邊框顏色的
- <padding androidLbottom = "xdp"...> 這個是設置邊距的
- <corners android:topLeftRadius="10px"...> 這個是設置圓角的
- <gradient> 這個是設置漸變色的,可選屬性有: startColor:起始顏色 endColor:結束顏色 centerColor:中間顏色 angle:方向角度,等於0時,從左到右,而後逆時針方向轉,當angle = 90度時從下往上 type:設置漸變的類型
實現效果圖:
代碼實現:
Step 1:編寫矩形邊框的Drawable:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <!-- 設置一個黑色邊框 --> <stroke android:width="2px" android:color="#000000"/> <!-- 漸變 --> <gradient android:angle="270" android:endColor="#C0C0C0" android:startColor="#FCD209" /> <!-- 設置一下邊距,讓空間大一點 --> <padding android:left="5dp" android:top="5dp" android:right="5dp" android:bottom="5dp"/> </shape>
Step 2:編寫圓角矩形邊框的Drawable:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 設置透明背景色 --> <solid android:color="#87CEEB" /> <!-- 設置一個黑色邊框 --> <stroke android:width="2px" android:color="#000000" /> <!-- 設置四個圓角的半徑 --> <corners android:bottomLeftRadius="10px" android:bottomRightRadius="10px" android:topLeftRadius="10px" android:topRightRadius="10px" /> <!-- 設置一下邊距,讓空間大一點 --> <padding android:bottom="5dp" android:left="5dp" android:right="5dp" android:top="5dp" /> </shape>
Step 3:將TextView的blackground屬性設置成上面這兩個Drawable:
<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:background="#FFFFFF" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/txtOne" android:layout_width="200dp" android:layout_height="64dp" android:textSize="18sp" android:gravity="center" android:background="@drawable/txt_rectborder" android:text="矩形邊框的TextView" /> <TextView android:id="@+id/txtTwo" android:layout_width="200dp" android:layout_height="64dp" android:layout_marginTop="10dp" android:textSize="18sp" android:gravity="center" android:background="@drawable/txt_radiuborder" android:text="圓角邊框的TextView" /> </LinearLayout>
在實際開發中,咱們可能會遇到這種需求:
如圖,要實現這種效果,可能你的想法是:一個ImageView用於顯示圖片 + 一個TextView用於顯示文字,而後把他們丟到一個LinearLayout中,接着依次建立四個這樣的小布局,再另外放到一個大的LinearLayout中,效果是能夠實現,可是會不會有點繁瑣呢?並且前面咱們前面也說過,佈局層次越少,性能越好!使用drawableXxx就能夠省掉上面的過程,直接設置四個TextView就能夠完成咱們的需求!
基本用法:
設置圖片的核心其實就是:drawableXxx;能夠設置四個方向的圖片: drawableTop(上),drawableButtom(下),drawableLeft(左),drawableRight(右) 另外,你也可使用drawablePadding來設置圖片與文字間的間距!
效果圖:(設置四個方向上的圖片)
實現代碼:
<RelativeLayout 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" tools:context="com.jay.example.test.MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:drawableTop="@drawable/show1" android:drawableLeft="@drawable/show1" android:drawableRight="@drawable/show1" android:drawableBottom="@drawable/show1" android:drawablePadding="10dp" android:text="張全蛋" /> </RelativeLayout>
一些問題: 可能你會發現,咱們這樣設置的drawable並不能自行設置大小,在XML是沒法直接設置的; 因此咱們須要在Java代碼中來進行一個修改!
示例代碼以下:
package com.jay.example.test; import android.app.Activity; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends Activity { private TextView txtZQD; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); txtZQD = (TextView) findViewById(R.id.txtZQD); Drawable[] drawable = txtZQD.getCompoundDrawables(); // 數組下表0~3,依次是:左上右下 drawable[1].setBounds(100, 0, 200, 200); txtZQD.setCompoundDrawables(drawable[0], drawable[1], drawable[2], drawable[3]); } }
運行效果圖:
代碼分析:
- ①Drawable[] drawable = txtZQD.getCompoundDrawables( ); 得到四個不一樣方向上的圖片資源,數組元素依次是:左上右下的圖片
- ②drawable[1].setBounds(100, 0, 200, 200); 接着得到資源後,能夠調用setBounds設置左上右下座標點,好比這裏設置了表明的是: 長是:從離文字最左邊開始100dp處到200dp處 寬是:從文字上方0dp處往上延伸200dp!
- ③txtZQD.setCompoundDrawables(drawable[0], drawable[1], drawable[2], drawable[3]);爲TextView從新設置drawable數組!沒有圖片能夠用null代替哦! PS:另外,從上面看出咱們也能夠直接在Java代碼中調用setCompoundDrawables爲 TextView設置圖片!
當文字中出現了URL,E-Mail,電話號碼,地圖的時候,咱們能夠經過設置autoLink屬性;當咱們點擊 文字中對應部分的文字,便可跳轉至某默認APP,好比一串號碼,點擊後跳轉至撥號界面!
看下效果圖:
all就是所有都包含,自動識別協議頭~ 在Java代碼中能夠調用setAutoLinkMask(Linkify.ALL); 這個時候能夠不寫協議頭,autolink會自動識別,可是還要爲這個TextView設置: setMovementMethod(LinkMovementMethod.getInstance()); 否則點擊了是沒效果的!
如題,除了顯示普通文本外,TextView還預約義了一些相似於HTML的標籤,經過這些標籤,咱們可使 TextView顯示不一樣的字體顏色,大小,字體,甚至是顯示圖片,或者連接等!咱們只要使用HTML中的一些 標籤,加上android.text.HTML類的支持,便可完成上述功能!
PS:固然,並非支持全部的標籤,經常使用的有下述這些:
- <font>:設置顏色和字體。
- <big>:設置字體大號
- <small>:設置字體小號
- <i><b>:斜體粗體
- <a>:鏈接網址
- <img>:圖片
若是直接setText的話是沒做用的,咱們須要調用Html.fromHtml()方法將字符串轉換爲CharSequence接口, 而後再進行設置,若是咱們須要相應設置,須要爲TextView進行設置,調用下述方法: Java setMovementMethod(LinkMovementMethod.getInstance())
嗯,接着咱們寫代碼來試試:
1)測試文本與超連接標籤
package jay.com.example.textviewdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.Html; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; import android.widget.TextView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView t1 = (TextView)findViewById(R.id.txtOne); String s1 = "<font color='blue'><b>百度一下,你就知道~:</b></font><br>"; s1 += "<a href = 'http://www.baidu.com'>百度</a>"; t1.setText(Html.fromHtml(s1)); t1.setMovementMethod(LinkMovementMethod.getInstance()); } }
運行效果圖:
恩呢,測試完畢~
2)測試src標籤,插入圖片:
看下運行效果圖:
接下來看下實現代碼,實現代碼看上去有點複雜,用到了反射(對了,別忘了在drawable目錄下放一個icon的圖片哦!):
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView t1 = (TextView) findViewById(R.id.txtOne); String s1 = "圖片:<img src = 'icon'/><br>"; t1.setText(Html.fromHtml(s1, new Html.ImageGetter() { @Override public Drawable getDrawable(String source) { Drawable draw = null; try { Field field = R.drawable.class.getField(source); int resourceId = Integer.parseInt(field.get(null).toString()); draw = getResources().getDrawable(resourceId); draw.setBounds(0, 0, draw.getIntrinsicWidth(), draw.getIntrinsicHeight()); } catch (Exception e) { e.printStackTrace(); } return draw; } }, null)); } }
嘿嘿,你也能夠本身試試,好比爲圖片加上超連接,點擊圖片跳轉這樣~
除了上面的HTML能夠定製咱們TextView的樣式外,還可使用SpannableString和SpannableStringBuilder來完成,二者區別:前者針對的是不可變文本,然後者則是針對可變文本,這裏只講解前者,對後者有興趣可自行查閱文本!
SpannableString可供咱們使用的API有下面這些:
- BackgroundColorSpan 背景色
- ClickableSpan 文本可點擊,有點擊事件
- ForegroundColorSpan 文本顏色(前景色)
- MaskFilterSpan 修飾效果,如模糊(BlurMaskFilter)、浮雕(EmbossMaskFilter)
- MetricAffectingSpan 父類,通常不用
- RasterizerSpan 光柵效果
- StrikethroughSpan 刪除線(中劃線)
- SuggestionSpan 至關於佔位符
- UnderlineSpan 下劃線
- AbsoluteSizeSpan 絕對大小(文本字體)
- DynamicDrawableSpan 設置圖片,基於文本基線或底部對齊。
- ImageSpan 圖片
- RelativeSizeSpan 相對大小(文本字體)
- ReplacementSpan 父類,通常不用
- ScaleXSpan 基於x軸縮放
- StyleSpan 字體樣式:粗體、斜體等
- SubscriptSpan 下標(數學公式會用到)
- SuperscriptSpan 上標(數學公式會用到)
- TextAppearanceSpan 文本外貌(包括字體、大小、樣式和顏色)
- TypefaceSpan 文本字體
- URLSpan 文本超連接
好吧,仍是蠻多的,這裏給出個最簡單的例子吧,其餘的參數調用可自行百度谷歌~ 1)最簡單例子: 運行效果圖:
實現代碼:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView t1 = (TextView) findViewById(R.id.txtOne); TextView t2 = (TextView) findViewById(R.id.txtTwo); SpannableString span = new SpannableString("紅色打電話斜體刪除線綠色下劃線圖片:."); //1.設置背景色,setSpan時須要指定的flag,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE(先後都不包括) span.setSpan(new ForegroundColorSpan(Color.RED), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //2.用超連接標記文本 span.setSpan(new URLSpan("tel:4155551212"), 2, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //3.用樣式標記文本(斜體) span.setSpan(new StyleSpan(Typeface.BOLD_ITALIC), 5, 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //4.用刪除線標記文本 span.setSpan(new StrikethroughSpan(), 7, 10, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //5.用下劃線標記文本 span.setSpan(new UnderlineSpan(), 10, 16, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //6.用顏色標記 span.setSpan(new ForegroundColorSpan(Color.GREEN), 10, 13,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); //7.//獲取Drawable資源 Drawable d = getResources().getDrawable(R.drawable.icon); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); //8.建立ImageSpan,而後用ImageSpan來替換文本 ImageSpan imgspan = new ImageSpan(d, ImageSpan.ALIGN_BASELINE); span.setSpan(imgspan, 18, 19, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); t1.setText(span); } }
2)實現部分可點擊的TextView 相信玩過QQ空間和微信朋友圈的朋友對下面的東東並不陌生吧,咱們能夠點擊 對應的用戶而後進入查看用戶相關的信息是吧!
下面咱們就來寫個簡單的例子來實現下效果:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView t1 = (TextView) findViewById(R.id.txtOne); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 20; i++) { sb.append("好友" + i + ","); } String likeUsers = sb.substring(0, sb.lastIndexOf(",")).toString(); t1.setMovementMethod(LinkMovementMethod.getInstance()); t1.setText(addClickPart(likeUsers), TextView.BufferType.SPANNABLE); } //定義一個點擊每一個部分文字的處理方法 private SpannableStringBuilder addClickPart(String str) { //讚的圖標,這裏沒有素材,就找個笑臉代替下~ ImageSpan imgspan = new ImageSpan(MainActivity.this, R.drawable.ic_widget_face); SpannableString spanStr = new SpannableString("p."); spanStr.setSpan(imgspan, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); //建立一個SpannableStringBuilder對象,鏈接多個字符串 SpannableStringBuilder ssb = new SpannableStringBuilder(spanStr); ssb.append(str); String[] likeUsers = str.split(","); if (likeUsers.length > 0) { for (int i = 0; i < likeUsers.length; i++) { final String name = likeUsers[i]; final int start = str.indexOf(name) + spanStr.length(); ssb.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { Toast.makeText(MainActivity.this, name, Toast.LENGTH_SHORT).show(); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); //刪除下劃線,設置字體顏色爲藍色 ds.setColor(Color.BLUE); ds.setUnderlineText(false); } },start,start + name.length(),0); } } return ssb.append("等" + likeUsers.length + "我的以爲很贊"); } }
運行效果圖:
核心其實就是:ClickableSpan的設置而已~你能夠本身搗鼓着寫下QQ空間評論的那個本身寫一個~
簡單說下什麼是跑馬燈,就是相似於web同樣,有一行字一直循環滾滾動這樣,好吧仍是看看 實現效果圖,一看就懂的了~
實現效果圖:
代碼實現:
<TextView android:id="@+id/txtOne" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" android:singleLine="true" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:focusable="true" android:focusableInTouchMode="true" android:text="你成天說着日了狗日了狗,可是你卻沒有來,呵呵呵呵呵呵呵呵呵呵~"/>
就像咱們平時編寫文檔的時候,咱們須要排版,設置下行或者字之間的間距是吧: Android中的TextView也能夠進行這樣的設置:
字間距:
android:textScaleX:控制字體水平方向的縮放,默認值1.0f,值是float Java中setScaleX(2.0f);
行間距: Android系統中TextView默認顯示中文時會比較緊湊,爲了讓每行保持的行間距
android:lineSpacingExtra:設置行間距,如"3dp" android:lineSpacingMultiplier:設置行間距的倍數,如"1.2"
Java代碼中能夠經過: setLineSpacing方法來設置
自動換行經過 android:singleLine 設置,默認爲 false。
如須要自動換行,能夠用:
android:singleLine = "false"
若是要在一行顯示完,不換行,能夠用:
android:singleLine = "true"
除此以外,能夠也設置多行顯示不完,添加個maxLines的屬性便可!
本節對Android中的TextView控件進行了詳細的解析,提供了開發中常見的一些問題的解決方法,相信 會爲你的實際開發帶來大大的便利,另外,筆者能力有限,寫出來的東西可能有些紕漏,歡迎指出, 不勝感激~另外,轉載請註明出處:coder-pig!謝謝~