转自https://blog.csdn.net/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">
...
...
恢复正常~