設定了背景圖片的TextView,其尺寸設定為wrap_content時,並不是適應文字內容大小
阿新 • • 發佈:2019-02-08
我們在做一些聊天對話方塊的介面設計時,經常會涉及到要寫一個 包含了對話方塊背景的TextView,一般來說 控制元件的寬高是使用wrap_content屬性
這個TextView背景設定為名為duihuakuang的圖片 <TextView android:id="@+id/tv_chatting_my_msg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="對話內容" android:background="@drawable/duihuakuang" android:textColor="@color/white"/>
這時,圖片尺寸稍大,而文字內容不多,效果如下:
可以說是非常醜,沒有任何一個軟體的對話方塊 會設計成這樣,一開始我很奇怪 為什麼明明TextView的尺寸是wrap_content,但是控制元件的大小卻不是適應文字內容呢?
折騰了一下,終於發現,這個wrap_content,字面意思就是 包含內容——也就是控制元件大小 適應內容的尺寸——而這個內容 不僅僅是指文字,android:background屬性也會影響控制元件大小。
就這個例子來說,這個TextView的背景設定了一個對話方塊圖片,同時也包含了“對話內容”四個字。那麼 這個wrap_content 究竟是包含誰的大小呢?——答案就是 都要包含,無論是TextView的背景圖片 還是TextView顯示的文字內容都要包含在這個控制元件中。所以就出現瞭如果你的背景圖片過大,那麼TextView可能就 除了包含文字以外,還會因為你的背景圖片過大而留出了大量空白,十分難看。
那麼怎麼辦呢?
個人總結三個辦法:
1)編寫一個shape作為TextView背景
2)找一張儘可能小的背景圖片(必須是.9.png格式,否則可能因為文字內容過多,導致 背景圖片被拉伸而失真)
ps: 1)方法就是在你的工程中的res/drawable目錄下,用程式碼"畫“圖,同時侷限性也很大,只能實現一些規則形狀的簡單圖形,具體方法網上有大量資料
具體程式碼示例如下:
Activity佈局 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="對話內容" android:background="@drawable/message_me"/> 這裡使用小圖片作為背景 ,達到了 對話方塊的大小能夠自適應 文字內容 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="對話內容" android:background="@drawable/duihuakuang"/> 這裡使用大圖片作為背景 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="對話內容" android:layout_marginTop="10dp" android:background="@drawable/background"/> 這裡使用shape作為背景 </LinearLayout>
shape的程式碼:
background
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
android:radius="10dp"/>
<stroke
android:color="@color/blue_light_2"
android:width="1dp"/>
<solid
android:color="@color/white"/>
</shape>
真機截圖:
部落格內容很簡單,可是我相信應該有不少和我一樣的新手遇到這個困擾,希望可以幫助到大家^ ^