无论 drawableLeft 如何将文本居中放置在 Button 中?
How to center the text inside a Button regardless of drawableLeft?
我希望文本居中 Button
。但是每当我将 android:drawableLeft
xml 属性添加到 Button
时,它都会偏移文本。我该如何解决?
我设法修复它的唯一方法是在 android:drawablePadding
中设置一个负数:
但我正在寻找更简洁的解决方案来实现它。
适用于:
android:gravity="center"
不幸的是,这就是 Button
行为,我同意你的观点,负填充是一种肮脏的黑客攻击,所以我会提出另外两个对我来说听起来不那么肮脏的黑客攻击,因为它们依赖于预期行为(负填充虽然有效但不是设计使然):
- 将按钮上的
android:paddingRight
设置为可绘制对象的大小
- 创建一个与左侧可绘制对象大小相同但全透明像素的可绘制对象,并将其作为右侧可绘制对象。
所以我最终采取了取其轻的做法,即将可绘制对象和文本放入 RelativeLayout
:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/Button.ButtonGray"
android:id="@+id/share_button">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/btn_share"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:textStyle="bold"
android:layout_centerInParent="true"
style="@style/TextNormalWeight"
android:text="@string/post_share"/>
</RelativeLayout>
然后 RelativeLayout
接收点击事件并表现得像一个按钮。
android:重力="center_vertical"
不幸的是,没有干净的方法来做到这一点。一种相当直接的方法是在按钮的另一侧设置一个大小相等的透明 ColorDrawable。
val drawableSize = button.height // adjust this as desired of course
realDrawable.setBounds(0, 0, drawableSize, drawableSize)
val emptyDrawable = ColorDrawable(Color.TRANSPARENT).apply {
setBounds(0, 0, drawableSize, drawableSize)
}
button.setCompoundDrawables(realDrawable, null, emptyDrawable, null)
我希望文本居中 Button
。但是每当我将 android:drawableLeft
xml 属性添加到 Button
时,它都会偏移文本。我该如何解决?
我设法修复它的唯一方法是在 android:drawablePadding
中设置一个负数:
但我正在寻找更简洁的解决方案来实现它。
适用于:
android:gravity="center"
不幸的是,这就是 Button
行为,我同意你的观点,负填充是一种肮脏的黑客攻击,所以我会提出另外两个对我来说听起来不那么肮脏的黑客攻击,因为它们依赖于预期行为(负填充虽然有效但不是设计使然):
- 将按钮上的
android:paddingRight
设置为可绘制对象的大小 - 创建一个与左侧可绘制对象大小相同但全透明像素的可绘制对象,并将其作为右侧可绘制对象。
所以我最终采取了取其轻的做法,即将可绘制对象和文本放入 RelativeLayout
:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/Button.ButtonGray"
android:id="@+id/share_button">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/btn_share"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:textStyle="bold"
android:layout_centerInParent="true"
style="@style/TextNormalWeight"
android:text="@string/post_share"/>
</RelativeLayout>
然后 RelativeLayout
接收点击事件并表现得像一个按钮。
android:重力="center_vertical"
不幸的是,没有干净的方法来做到这一点。一种相当直接的方法是在按钮的另一侧设置一个大小相等的透明 ColorDrawable。
val drawableSize = button.height // adjust this as desired of course
realDrawable.setBounds(0, 0, drawableSize, drawableSize)
val emptyDrawable = ColorDrawable(Color.TRANSPARENT).apply {
setBounds(0, 0, drawableSize, drawableSize)
}
button.setCompoundDrawables(realDrawable, null, emptyDrawable, null)