22

解谜:为何用了9-Patch背景图后自带Padding属性?

 3 years ago
source link: http://www.cnblogs.com/wenhanxiao/p/13867138.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

本次分享的主题源于笔者在实际开发中遇到的问题。

具体现象为:当普通的9-Patch图用作TextView的backGround属性后,整个TextView便有了一定的Padding值。但笔者并没有给定padding属性,甚至在预览视图中,也没有展现出padding效果。但运行起来后,便莫名其妙地有了内边距。

我们先来看布局代码:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_gravity="center"
    android:background="@mipmap/background"
    android:text="@string/app_name"
    tools:context=".MainActivity">
    
</TextView>

在Android Studio内的界面预览如图:

UnUb6fA.png!mobile

红色边框的图片即背景,是经过9-Patch处理过的.9.png文件。

显然,在预览时是正常没有内边距的,接下来我们运行它。其效果如下图所示:

EB3mQjm.png!mobile

可以看到,实际运行时,内边距出现了。

经过一番问题排查,发现其根源在于.9.png文件,在Android Studio中打开这个图片,发现它的缩放设定是这样的:

3aENruN.png!mobile

可见,中央深粉色的部分就是自由拉伸的部分。定义它的,则是图片四周的黑色线条。

接着,我们勾选“Show content”,即预览显示内容区,如下图所示:

fyEnyem.png!mobile

可见,内容仅显示在中央非空白区域,也就是我们最终看到的运行效果了。

到此,问题的根源找到了,我们怎么解决它呢?很简单,在进行图片拉伸定义时,我们应使用上和左边缘进行划线定义,而右和下边缘则定义了内容可填充的区域。因此,做如下图所示的修改:

qiyQren.png!mobile

分别仔细观察上侧和下侧,左侧和右侧边缘,可以看到上侧和下侧并非完全划线,而是定义了拉伸的部分;而下侧和右侧则是完全划线,限定了内容可填充区域。

再次运行,可见内边距已消失。

AjMJriE.png!mobile

当然,还有一种解决办法。即在xml布局文件中,将TextView的padding属性值强制写为0dp,内边距则也会为0。但笔者更推荐使用前一种方法,因为强制为0的方法,在当确实需要有padding值的时候,往往会不太好处理。

好了,以上就是本次分享给大家的开发小技巧,希望能够对你有所帮助。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK