Android Button设置背景后drawableBottom间距过大,如何优化?
我尝试在Button文字下方添加一个红点,但使用drawableBottom时默认间距过大;移除背景drawable后,间距恢复正常。相关XML代码如下:
Dot drawable代码
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="oval"> <solid android:color="#fff"/> <size android:height="5dp" android:width="5dp"/> </shape> </item> </selector>
Background drawable代码
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="rectangle"> <solid android:color="#000"/> </shape> </item> </selector>
Button代码
<Button android:id="@+id/button" style="?android:attr/buttonBarButtonStyle" android:layout_width="0px" android:layout_height="match_parent" android:layout_weight="1" android:background="@drawable/background" android:drawableBottom="@drawable/dot" android:drawableTint="#FF0000" android:insetTop="0dp" android:insetBottom="0dp" android:text="-" app:cornerRadius="0px" />
解决方案(保留背景前提下缩小间距)
以下几种方法可解决该问题:
调整Drawable内部边距
在dot drawable中添加负的顶部内边距,拉近红点与文字的距离,数值可按需调整:<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:shape="oval"> <solid android:color="#fff"/> <size android:height="5dp" android:width="5dp"/> <!-- 负padding缩小间距,避免过度偏移导致红点被裁剪 --> <padding android:top="-4dp"/> </shape> </item> </selector>使用
drawablePadding属性
在Button标签中直接设置drawablePadding为负值,控制文字与drawable的间距:<Button android:id="@+id/button" style="?android:attr/buttonBarButtonStyle" android:layout_width="0px" android:layout_height="match_parent" android:layout_weight="1" android:background="@drawable/background" android:drawableBottom="@drawable/dot" android:drawableTint="#FF0000" android:insetTop="0dp" android:insetBottom="0dp" android:drawablePadding="-4dp" <!-- 添加该行控制间距 --> android:text="-" app:cornerRadius="0px" />自定义Button布局
若上述方法效果不佳,可通过布局组件自定义Button样式,精准控制间距:<LinearLayout android:id="@+id/custom_button" android:layout_width="0px" android:layout_height="match_parent" android:layout_weight="1" android:background="@drawable/background" android:orientation="vertical" android:gravity="center"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="-" android:textColor="#fff"/> <View android:layout_width="5dp" android:layout_height="5dp" android:background="@drawable/dot" android:layout_marginTop="2dp"/> <!-- 直接设置红点与文字的间距 --> </LinearLayout>后续在代码中给该布局添加点击事件即可。
内容的提问来源于stack exchange,提问作者stormyholidays
相关产品推荐
相关产品推荐

