Android layout中9-patch设为背景图片后遮挡其它空间问题

转自https://blog.youkuaiyun.com/houshunwei/article/details/6727433 ,鸣谢!

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bkgrd_main">

    <Button
        android:id="@+id/btn_1"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="24dp"
        app:layout_constraintBottom_toTopOf="@id/btn_2" />

    <Button
        android:id="@+id/btn_2"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="24dp"
        app:layout_constraintBottom_toTopOf="@id/btn_3" />

    <Button
        android:id="@+id/btn_3"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="40dp"
        app:layout_constraintBottom_toBottomOf="parent" />
</android.support.constraint.ConstraintLayout>

如图,设9patch为背景图后,几个button无法显示,且边距也有问题:40dp怎么可能会这么高。

原因是9patch自带了padding属性:

public void setBackgroundDrawable (Drawable d) Since: API Level 1 Set the background to a given Drawable, or remove the background. If the background has padding, this View's padding is set to the background's padding. However, when a background is removed, this View's padding isn't touched. If setting the padding is desired, please use setPadding(int, int, int, int).Parametersd The Drawable to use as the background, or null to remove the background

只要把padding手动设置一下覆盖掉它自带的padding就行了:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="0dp"
    android:background="@drawable/bkgrd_main">

...
...

恢复正常~

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值