您的位置:首页 > 其它

TextView使用wrap_content设置高度,上下有间隔 去除的方法,两种

2017-10-20 11:07 435 查看
  最近在开发程序的时候,发现自己的布局,明明是按照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 改为固定高度的

以上本人均试过,没卵用,各位如果喜欢,可以再试一次

以下为本人的解决办法

直接上效果和代码

<?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>
bg_tv.xml的布局

<?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把布局的每个控件与基准线的高度都测量一下,即可,或者你有时间自己测量也行!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐