TextView使用wrap_content設定高度,上下有間隔 去除的方法,兩種
最近在開發程式的時候,發現自己的佈局,明明是按照UI給的dp的高度來時來設定的,但是實際效果,總是出現高度出現比較大的誤差,之前一直找自己是不是什麼地方佈局錯了,或者螢幕適配有問題,後來一通認真查詢,TextView設定背景的時候,才發現原來一直使用的TextVew 本身有問題, 左右的寬度是包裹的,但是上下的高度確總是有間距!!!
為了解決這個問題,自己網上找了不下60-70篇解決文章,發現沒幾個有卵用的,
網上提供的解決方式,以下幾種比較高的瀏覽量的(沒卵用):
1.android:includeFontPadding="false"
2.padding 全部設定為0,0,0,0
3.padding 上下設定為負數
4.網上找的寫的解決這個問題的自定義控制元件,繼承TextView的. 如:http://m.blog.csdn.net/qq_27489007/article/details/78063346
5.warp_content 改為固定高度的
以上本人均試過,沒卵用,各位如果喜歡,可以再試一次
以下為本人的解決辦法
直接上效果和程式碼
bg_tv.xml的佈局<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <com.sz.quxin.demotextview.FitHeightTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/colorAccent" android:includeFontPadding="false" android:text="Hello World!" android:textColor="#56BBe0" android:textSize="28sp"/> <TextView android:background="@drawable/bg_tv" android:layout_marginTop="-5dp" android:includeFontPadding="false" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/app_name" android:textColor="@color/colorAccent" android:textSize="28sp"/> </LinearLayout>
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="@android:color/holo_orange_dark"/> <corners android:radius="0dp"></corners> <padding android:bottom="-5dp" android:top="-5dp"/> <stroke android:width="0.6dp" android:color="@android:color/holo_green_dark"/> </shape>
效果圖
採用給TextView設定背景.背景裡面設定padding 為負數,另外TextViewlayout_marginTop="-5dp"設定負數,則這個問題就得到了比較好的解決.但是如果有很多字型大小的TextView,都這樣設定,就比較繁瑣了,在github上找了兩天別人寫的自定義,也沒有找到好的,如果有能解決這個問題的,自定義TextView,記得推薦下,後續準備有空自己寫一個自定義的TextView,專門解決這個問題.
注意事項:
在使用的時候,上下建議最好不要採用百分比佈局 左右無所謂.
另外不想每次這麼麻煩:還有一個解決方式:
採用相對佈局,但是所有的控制元件的都已最頂層的開始基準線為參考物件,不要採用below或者above的寫法,這樣控制元件與控制元件上下TextView等控制元件上下空白的地方,就會相互重疊,但是又不會遮擋和字型,唯一的要求,就是讓UI把佈局的每個控制元件與基準線的高度都測量一下,即可,或者你有時間自己測量也行!